- Hands-On Full Stack Development with Go
- Mina Andrawos
- 329字
- 2021-07-02 12:33:30
Variables and data types
A variable is another basic building block of the Go language. In Go, to declare a variable, you can simply use the var keyword. Here is what this looks like:
var s string
Obviously, string is the data type. Let's say we would like to declare more than one variable of type string on the same statement. Here is what this would look like:
var s1,s2,s3 string
To initialize a variable with an initial value, Go offers a number of options. One option is to initialize the variable while also specifying the variable type. Here is what this looks like:
var s1,s2,s3 string = "first-string", "second-string", "third-string"
Another option is to initialize the variables without specifying the data type. Here is what this would look like:
var s1,s2,s3 = "first-string", "second-string", "third-string"
We can then mix data types with the following syntax:
var s,i,f = "mystring",12,14.53
A popular way to declare and initialize multiple variables at once is as follows:
var (
s = "mystring"
i = 12
f = 14.53
)
If you are declaring and initializing your variable inside a function, you don't need to even use the var keyword. Instead, you can use :=. This is called type inference, since you infer the variable type from the provided value. Here is how we would declare and initialize the s, i, and f variables with type inference:
s := "mystring"
i := 12
f:=14.53
The var keyword, however, gives you more control since it allows you to explicitly specify the data type you would like to use for your variable.
Now, let's discuss data types. Go has a standard set of data types that are very similar to data types you'd find in any other statically typed programming language. Here is a summary of Go's standard data types:

Variables that are declared without an explicit initial values get assigned what is known as zero values. Here is a table for zero values:

- 一步一步學Spring Boot 2:微服務項目實戰
- INSTANT FreeMarker Starter
- C語言程序設計案例精粹
- 基于Swift語言的iOS App 商業實戰教程
- Learning Python by Building Games
- Python數據結構與算法(視頻教學版)
- Scratch趣味編程:陪孩子像搭積木一樣學編程
- HoloLens與混合現實開發
- 人工智能算法(卷1):基礎算法
- FPGA嵌入式項目開發實戰
- Nagios Core Administration Cookbook(Second Edition)
- PhoneGap 4 Mobile Application Development Cookbook
- Elasticsearch搜索引擎構建入門與實戰
- 絕密原型檔案:看看專業產品經理的原型是什么樣
- Unreal Engine Game Development Cookbook