const aa, bb, cc = "eat", 2, "ok" const ( a = iota b c )
默认值
golang中所有的变量都是初始化过的。
类型
初始值
int
0
float
0.0
bool
false
string
""
pointer
nil
变量赋值
1 2 3
var a, b, c int a, b, c = 1, 2, 3 a, b = b, a
Variables can be redeclared in short multi-variable declarations where at least one new variable is introduced. Redeclaration does not introduce a new variable; it just assigns a new value to the original.
1 2 3 4 5
funcmain() { m := 0 m, n := 1, 2 fmt.Println(m, n) }
strings.Fields(s) []string// split with space strings.Split(s, sep) []string// split with sep strings.Join(sl []string, sep string) string// join with sep
1 2 3 4 5 6 7 8 9 10 11
// gives only the bytes: for i:=0; i < len(str); i++ { c := str[i] } // gives the Unicode characters: for ix, ch := range str { unicode_c := str[i] }
// ERROR: loop variable will not go closure package main
import ( "fmt" "time" )
funcgoroutineRun(values []int) { for value := range values { gofunc() { time.Sleep(1 * time.Second) fmt.Println(value) // ERROR: value is not what we want }() } }
// Ternary return value as: // condition ? left : right // don't user condition as nil-check that value depends on condition, such as // Ternary(ptr != nil, ptr.value, 0) // will panic because ptr.value is param that need to be calculated when Ternary called. funcTernary[Tany](b bool, left T, right T)T { if b { return left } else { return right } }
funcmain() { // Here are some calculations with bigInts: im := big.NewInt(math.MaxInt64) in := im io := big.NewInt(1956) ip := big.NewInt(1) ip.Mul(im, in).Add(ip, im).Div(ip, io) fmt.Printf("Big Int: %v\n", ip) // Here are some calculations with bigInts: rm := big.NewRat(math.MaxInt64, 1956) rn := big.NewRat(-1956, math.MaxInt64) ro := big.NewRat(19, 56) rp := big.NewRat(1111, 2222) rq := big.NewRat(1, 1) rq.Mul(rm, rn).Add(rq, ro).Mul(rq, rp) fmt.Printf("Big Rat: %v\n", rq) }
/* Output: Big Int: 43492122561469640008497075573153004 Big Rat: -37/112 */
package
1 2 3 4
import"github.com/spf13/cobra"// normal import import mycobra "github.com/spf13/cobra"// import as mycobra import _ "github.com/spf13/cobra"// init function of cobra called import _ "image/png"// register PNG decode
模块替换,本地开发时使用:
1
replace example.com/modulename => ../localmodule
模块初始化:
Package-level variables are initialized in declaration order, but after any of the variables they depend on.
Initialization of variables declared in multiple files is done in lexical file name order. Variables declared in the first file are declared before any of the variables declared in the second file.
Initialization cycles are not allowed.
Dependency analysis is performed per package; only references referring to variables, functions, and methods declared in the current package are considered.
Directory and file names that begin with “.” or “_” are ignored by the go tool, as are directories named “testdata”.
switch t := arg.(type) { case *Square: fmt.Println("is square") case *Circle: fmt.Println("is circle") default: fmt.Printf("unexpected type %T\n", t) }
var ( firstName, lastName, s string i int f float32 input = "56.12 / 5212 / Go" format = "%f / %d / %s" )
funcmain() { fmt.Println("Please enter your full name: ") fmt.Scanln(&firstName, &lastName) // fmt.Scanf("%s %s", &firstName, &lastName) fmt.Printf("Hi %s %s!\n", firstName, lastName) // Hi Chris Naegels fmt.Sscanf(input, format, &f, &i, &s) fmt.Println("From the string we read: ", f, i, s) // 输出结果: From the string we read: 56.12 5212 Go }
select { case resp := <-ch // data pushed into ch, or ch closed. case <-time.After(timeoutNs) // timeout }
Tag
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
type Person struct { Name string`json:"name"` Age int`json:"age"` Addr string`json:"addr,omitempty"` }
// 三种获取 field field := reflect.TypeOf(obj).FieldByName("Name") field := reflect.ValueOf(obj).Type().Field(i) // i 表示第几个字段 field := reflect.ValueOf(&obj).Elem().Type().Field(i) // i 表示第几个字段