This is a creation in Article, where the information may have evolved or changed.
Golang Basic Grammar (1)
Declaration of a variable
In the go package, a variable or method function or constant starts with a capital letter and can be seen outside of the package.
Either a package variable or a package method or a package constant that can be exported
Lowercase package variables and package methods There are package constants that can only be accessed within the package
//定义一个变量,名称为 "numberOfTimes",类型为 "int"var numberOfTimes int//定义三个变量,类型为 “int"var var1, var2, var3 int//定义一个变量,名称为 "numberOfTimes",类型为 "int",值为 "3"var numberOfTimes int = 3//定义三个类型为 "int" 的变量,并且初始化它们的值var var1, var2, var3 int = 1, 2, 3
package main//var foo string//foo := "test"func main(){ var bar int foo1 := 10 //v1 v2 v3可以是任意类型,编译器会自动确认数据类型 vname1, vname2, vname3 := v1, v2, v3 //下面的 var1 := 11会报错,因为变量 var1已经被定义,不能重复定义 var var1 int = 10 var1 := 11 //下面正确,只是给 var2重新赋值 var var2 int = 10 var2 = 12}
A package or variable that is not used in the Go language can cause compilation to fail
//"net/http" 包导入不使用,如果包里面有 init 方法,只执行 init 方法import( "fmt" _ "net/http")func main(){ //函数 divede 返回值第一个放弃不使用 _, remainder := divide(10, 3)}
//导入包import( "fmt" "os")//常量定义const( i = 100 pi = 3.1415 prefix = "Go_")//变量var( i int pi float32 prefx string)//结构体type( people struct{ name string age int } animal struct{ name string leg int })
const( x = iota // x == 0 y = iota // y == 1 z = iota // z == 2 w // 省略 iota ,w == 3)const( a = iota // a == 0 b = 10 c // c == 1 d // d == 2)const v = iota //v ==0const( e, f, g = iota, iota, iota // e==0, f==0, g==0 因为在同一行)
Attributes of the base data type
Wrong type error types
Go has no exception handling mechanism, built-in error type, for handling errors
Go requires that we either explicitly handle an error or ignore
Array, slice, map
var arr [n]typea := [3]int{1, 2, 3}//... 自动识别数组长度a := [...]int{1,3,3}d := [2][2]int{[2]int{0,0}, [2]int{2,2}}d1 := [2][2]int{{1,1}, {22,22}}
var fslice []intslice := []byte{'a', 'c', 'd'}
a := []int{1,2,3,5}b := a[1:] // b 为 2,3,5 但是 a b 共享底层数据结构,修改 a 或者 b , a和 b 都会改变b := a[:2] // b 为 1, 2
The index of the slice can only be the int,map of any type you want
numbers := make(map[string]int)numbers["one"] = 1
Make New difference
Make allocates memory to built-in types and initializes them, returning non-0 values
New (T) returns a value of 0
Control structures and functions
if test {}//分号隔开,赋值if x := len(slice); x >0 {}
func my(){ i := 0Here: //label goto i++ goto Here //跳转到 Here}
func funcName(p1 type1, p2 type2)(returnType1, returnType2{ return a, b}func varFunc(arg1 ...int){}
import( . ”fmt" //忽略包名 o "os" //别名 _ "net/http" //导入包执行 init 方法不使用)
Not to be continued