[TOC]
I. Variables 1. Declaring variables
A variable is a name for a piece of data storage space, and the program can request a chunk of data storage by defining a variable, which can then be used by referencing the variable name.
Go语言引入了关键字var,而类型信息放在变量名之后,变量声明语句不需要使用分号作为结束符,示例如下:varintvarstringvar v3 [10]int// 数组var v4 []int// 数组切片varstructint}var v6 *int// 指针varmap[string]int// map, key为string类型, value为int类型varfuncintint
Another use of the Var keyword is to put several variables that need to be declared together, lest the programmer need to repeat
Write the var keyword as follows:
varintstring)
The var keyword can be preserved for scenarios that require initialization when declaring variables, but are no longer necessary elements:
varint10// 正确的使用方式1var10// 正确的使用方式2,编译器可以自动推导出v2的类型10// 正确的使用方式3,编译器可以自动推导出v3的类型
Combination of a colon and an equal sign: =, used to explicitly express the work of declaring and initializing variables simultaneously.
Cannot repeat declaration:
varint2new variables on left side of :=
2. Anonymous variables
_ is a special identifier used to ignore the result
package mainimport( "fmt")funcintint)(int,int) { sum := a + b avg := (a+b)/2 return sum, avg}func main() { _,avg := cal(100,200) fmt.Println(avg)}
Second, constant
In the go language, constants refer to values that are known and immutable during compilation. Constants can be numeric types (including integer, float, and complex types), Boolean types, string types, and so on.
constfloat643.14159265358979323846const0.0// 无类型浮点常量const ( int641024 eof = -1// 无类型整型常量)constfloat3203// u = 0.0, v = 3.0,常量的多重赋值const34"foo"// a = 3, b = 4, c = "foo", 无类型整型和字符串常量
Define two constants a=1 and b=2, get the number of seconds in the current time, and if it can be divisible by B, print B at the terminal, otherwise print a.
package mainimport( "fmt" "time")const ( 1 2)func main() { for { second := time.Now().Unix() fmt.Print(second," ") if0) { fmt.Println("b") else { fmt.Println("a") } time.Sleep(1000 * time.Millisecond) }}
Iii. data type 1. Integral type
Type length (bytes) value rangeint8 1- -~127Uint8 (that is, byte)1 0~255Int16 2-32768~32767uint16 2 0~65535Int32 4-2147483648~2147483647UInt32 4 0~4294967295Int64 8-9223372036854775808~9223372036854775807UInt64 8 0~18446744073709551615intPlatform-related platform relatedUINTPlatform-related platform relatedUIntPtrThe same pointer is 4 bytes under the 32-bit platform, -Bit platform is 8 bytes
For conventional development, it is possible to use int and uint, and there is no need to explicitly specify length types such as int8 to avoid porting difficulties.
varint3264// value1将会被自动推导为int类型// 编译错误编译错误类似于:cannot use value1 (typeinttypeint32int32// 编译通过
eg
package mainimport"fmt"func main() { varint1616 varint32 //m=n int32(n) fmt.Printf("32 bit int:%d\n",m) fmt.Printf("16 bit int:%d\n",n)}
2.bool
varbooltruev2 := (12// v2也会被推导为bool类型varboolb = (1!=0// 编译正确fmt.Println("Result:"// 打印结果为Result: true
3. Numerical operations
Go语言支持下面的常规整数运算: +、 -、 *、 /和%。 % 和在C语言中一样是求余运算,比如:5 % 3 // 结果为: 2
4. Floating-point type
The go language defines two types of float32 and float64, where float32 is equivalent to the float type of C, and float64 is equivalent to the double type of the C language.
varfloat321212.0// 如果不加小数点, f2会被推导为整型而不是浮点型float32(f2)//强制类型转换
Because floating-point numbers are not an exact representation, it is not feasible to use = = as an integer to determine whether two floating-point numbers are equal, which can lead to unstable results.
The following is a recommended alternative:
import"math"// p为用户自定义的比较精度,比如0.00001funcfloat64bool { return math.Fdim(f1, f2) < p}
Exercise: Generate 10 random integers using Math/rand, 10 random integers less than 100, and 10 random floating-point numbers
package mainimport ( "fmt" "math/rand" "time")func init() { rand.Seed(time.Now().UnixNano())}func main() { for010; i++ { a := rand.Int() fmt.Println(a) } for010; i++ { a := rand.Intn(100) fmt.Println(a) } for010; i++ { a := rand.Float32() fmt.Println(a) }}
5. Characters
Two character types are supported in the go language, one is a byte (actually an alias of Uint8), a single byte value representing the UTF-8 string, and the other is Rune, which represents a single Unicode character. For the sake of simplifying the language, most APIs in the go language assume that the string is UTF-8 encoded. Although Unicode characters are supported in the standard library, they are actually less used.
Byte.go
package mainimport"fmt"func main() { varbyte for b =0;b<177;b++{ fmt.Printf("%d %c\n",b,b) }}
Rune.go
package mainimport"fmt"func main() { // byte => uint8 // rune => int32 "golang你好" fmt.Println(len(s)) 0 forrange s { 1 fmt.Printf("%c\n", r) } fmt.Println("cnt", cnt) ss := []rune("hello") fmt.Println(ss)}
6. String type
PackageMainImport "FMT"funcMain () {str: ="Hello, the World"N: =Len(str) FMT. PRINTLN (N) forI: =0; I < n; i++ {ch: = Str[i]//According to the subscript to take the character in the string, the type is byteFmt. Println (i, ch)} FMT. Println ("///////////////////////////") STR1: ="Hello, the World" forI, ch: =Rangestr1 {fmt. Println (i, CH)the type of//ch is Rune}}/* A01 1012 1083 1084 11156 2287 18489 231Ten 149 One///////////////////////////01 1012 1083 1084 11156 199909 30028*/
Traversed as an array of bytes: This string is 12 in length. Although intuitively, this string should be only 10 characters. This is because each Chinese character occupies 3 bytes in UTF-8, not 1 bytes.
Traversing with Unicode characters: when traversing in Unicode characters, the type of each character is Rune (the earlier Go language uses the int type to represent Unicode characters), rather than byte.
Iv. value types and reference types
Value types: base data type int, float, bool, string, and array and struct.
Reference types: pointers, slice, maps, Chan, and so on are reference types.
The difference between value semantics and referential semantics is the assignment of values, such as the following example:
b = A
B.modify ()
If the modification of B does not affect the value of a, then this type belongs to the value type. If the value of a is affected, then this type is a reference type.
Most types in the go language are based on value semantics, including:
Basic types, such as Byte, int, bool, float32, float64, and string;
Composite types, such as array, struct (struct), and pointer (pointer).
package mainimport"fmt"func main(){ var a = [3]int{123} var b = a b[1]++ fmt.Println(a)// [1 2 3] fmt.Println(b)//[1 3 3]}
A b=a assignment statement is a complete copy of the contents of an array. To express a reference, you need to use the pointer
package mainimport"fmt"func main(){ var a = [3]int{123} var b = a var c = &a b[1]++ c[1]++ fmt.Println(a) fmt.Println(b) fmt.Println(*c) /* [1 3 3] [1 3 3] [1 3 3] */}
The C=&a assignment statement is a reference to the contents of the array. The type of variable c is not [3]int, but *[3]int type
Exercise: Write a program to print value types and reference type variables to the terminal, and observe the output
package mainimport ( "fmt")funcint) { 50 return}func modify1(a *int) { 500}func main() { 5 make(chanint1) fmt.Println("a=", a) fmt.Println("b=", b) modify(a) fmt.Println("a=", a) modify1(&a) fmt.Println("a=", a)}
Exercise: Write a program that swaps the values of two integers.
package mainimport"fmt"funcintint) { tmp := a a = b b = tmp return}func main() { 1 2 swap(one,two) fmt.Println("one=",one) fmt.Println("two=",two)}
dumbfounded, not change! Asterisking number!
package mainimport"fmt"func swap(a *int, b *int) { tmp := *a *a = *b *b = tmp return}funcintint) (int,int){ return b,a}func main() { 1 2 swap(&one,&two) //one,two=swap2(one,two) //one,two=two,one fmt.Println(one,two)}
V. Scope of variables
1. Variables declared inside the function are called local variables, and the life cycle is limited to the inside of the function.
2. Variables declared outside the function are called global variables, and the life cycle acts on the entire package, and if it is uppercase, it acts on the entire program.
package mainimport"fmt"var"Greg"func aa() { fmt.Println(a)}func ab() { "ningxin" fmt.Println(a)}func ac() { 2 fmt.Println(a)}func main() { aa() ac() aa() ab() aa()}
A: = 2 cannot be a global variable, because this is not a declaration, but rather the execution of code, the code block in the function, the go program from the top to the next part of the code block can only be declared.
varint a=2
Output what?
package mainimport"fmt"varstringfunc f1() { "ningxin" fmt.Println(a) f2()}func f2() { fmt.Println(a)}func main() { "greg" fmt.Println(a) f1()}
Go development [Two]:golang language basics