Go language basics
keywords
break
, default
, func
, interface
, select
case
, defer
, go
, map
, struct
chan
, else
, goto
, package
, switch
const
, fallthrough
, if
, range
, type
continue
, for
, import
, return
, var
define variable
var variablename type = value
var vname1, vname2, vname3 type = v1, v2, v3
- Type declarations can be ignored, and Go will initialize based on the corresponding value type:
var vname1, vname2, vname3 = v1, v2, v3
- Continue to simplify:
vname1, vname2, vname3 := v1, v2, v3
,:=
replacesvar
andtype
, this form is called short statement. However, it has a limitation and can only be used inside a function; if it is used outside a function, it will not compile, so it is generally used tovar
define global variables . _
The underscore is a special variable name, and any value assigned to it is discarded:_, b := 1, 2
Go will report an error at compile time for variables that are declared but not used
package main func main() { var i int //报错,声明了i但未使用 }
constant
Constants can be defined as numeric, boolean, or string types
const constantName = value //如果需要也可以明确指定常量的类型 const Pi float32 = 3.1415926
Built-in base types
Boolean
var isActive bool //全局变量 var enable, disable = true, false //忽略类型的声明 func test() { var available bool //一般声明 valid := false //简短声明 vaailable = true //赋值操作 }
- Numeric type
- There are two types of integer types, unsigned and signed. Signed:
rune
,int8
,int16
,int32
,int64
; Unsigned:byte
,uint8
,uint16
,uint32
,uint64
. of whichrune
yesint32
aliasesbyte
yesuint8
aliases float32
There are two types of floating point numbersfloat64
, the default isfloat64
Complex number, the default type is
complex128
(64-bit real number + 64-bit imaginary number),complex64
(32-bit real number + 32-bit imaginary number); complex number form:RE + IMi
var c complex64 = 5 + 5i
- These types of variables are not allowed to assign or operate each other, otherwise the compiler will report an error at compile time
- string
statement
var sName string //声明变量为字符串的一般方法 var sName1 string = "" //声明一个字符串变量,并赋值为空 func test() { a, b, c := "no", "yes", "maybe"//简短声明 }
Strings are immutable in Go
var s string = "hello" s[0] = "c" //cannot assign to s[0]
how to change string
s := "hello" c := []byte(s) //将字符串 s 转换为 []byte 类型 c[0] = "c" s2 := string(c) //再转换为 string 类型 fmt.Printf("%s\n", s2)
- String concatenation
+
- string slice
s[start: end]
Declare a multi-line string
m := `hello world`
group statement
import( "fmt" "os" ) const( i = 100 pi = 3.1415 s = "hello" ) var( i int pi float32 s string )
iota enumeration, this keyword is used
enum
when declaring, the default starting value is 10
forconst
each additional linepackage main import ( "fmt" ) const ( x = iota // x == 0 y = iota // y == 1 z = iota // z == 2 w //常量声明省略值时,默认和之前一个值的字面意思相同。这里隐式表达`w = iota`,因此`w == 3`。 ) const v = iota //每遇到一个const关键字,iota就会重置,此时v == 0 const ( h, j, k = iota, iota, iota //h==0, j == 0, k == 0 iota在同一行 ) const ( a = iota // a == 0 b = "hi" c = iota // c == 2 d, e, f := iota, iota, iota // d == 3, e == 3, f == 3 g = iota // g == 4 )
- array
statement
var arr [n]type //n-->length, type-->存储元素的类型 a := [3]int{1, 2, 3} //声明一个长度为3的int数组 b := [10]int{1, 2, 3} //声明一个长度为10的int数组,其中前三个元素赋值1、2、3,其他默认为0 c := [...]int{4,5,6} //省略长度,go会根据元素个数来计算长度 twoDarr := [2][4]int{[4]int{1, 2, 3, 4}, [4]int{5, 6, 7, 8}} //声明二维数组 simple := [2][4]int{{1,2,3,4},{5,6,7,8}} //简化声明,忽略内部类型
- slice
- In many application scenarios, arrays cannot meet our needs. When we initially define the array, we don't know how big we need to be, so we need "dynamic arrays". In GO, this data structure is called
slice
slice
Not really a dynamic array, but a reference type.slice
always points to an underlying layerarray
,slice
the declaration can also be like thearray
same, only the length is not requiredvar fslice []int //和声明数组一样,只是少了长度 //声明一个slice,并初始化数据 slice := []byte{"a", "b", "c", "d"} //slice可以从一个数组或一个已经存在的slice中再次声明 var arr = [6]byte{"a", "b", "c", "d", "e", "f"} var a, b []byte a = arr[1:3] b = arr[3:]
slice
The built-in function
len
gets theslice
length ,
cap
gets theslice
capacity , appends one or more elements
append
toslice
it, and returns a functionslice
of the same type. Copy copies the elementsslice
copy
from the source toslice
thesrc
destinationdst
, and returns the number of copied elements. The
append
function changesslice
the contents of the referenced array. , thus affecting other references to the same arrayslice
//三参数的slice var arr [10]int slice := arr[2:4] //slice的容量为10-2=8 newSlice := arr[2:4:7] //slice的容量为7-2=5,无法访问最后的三个元素
map
The format ismap[keyType]valueType
, similar to the concept of a dictionary in python//声明一个key是字符串,值为int的字典,这种方式的声明需要在使用之前使用make初始化 var number map[string]int //另一种map的声明方式 numbers = make(map[string]int) numbers["one"] = 1 //赋值
map
It is unordered, and it will be different every time it is printed.map
It must be obtained bykey
obtaining
- The length is not fixed, it is a reference type, if two
map
point to the same bottom layer at the same time, then one changes, and the other changes accordingly
- The built-in
len
function also worksmap
, returning the number ofmap
possessionskey
- elements that can be
delete
removed bymap
make
Andnew
operations are used for memory allocation of
make
built-in types (map
,slice
, ). for various types of memory allocationschannel
new