package mainimport "fmt"func main() { fmt.Println("Hello, world!")}
直接运行
$ go run hello.goHello, world!
或者在 Go repl 中尝试一下
var s1 strings1 = "Learn Go!"// 一次声明多个变量var b, c int = 1, 2var d = true
简短声明
s1 := "Learn Go!" // stringb, c := 1, 2 // intd := true // bool
参见:基本类型
package mainimport "fmt"// 程序的入口点func main() { fmt.Println("Hello world!") say("Hello Go!")}func say(message string) { fmt.Println("You said: ", message)}
参见:函数(Functions)
// 单行注释/* 这是多行注释 */
if true { fmt.Println("Yes!")}
参见:条件控制
s1 := "Hello" + "World"s2 := `A "raw" string literalcan include line breaks.`// 输出:10fmt.Println(len(s1))// 输出:Hellofmt.Println(string(s1[0:5]))
字符串的类型为 字符串
num := 3 // intnum := 3. // float64num := 3 + 4i // complex128num := byte('a') // byte (alias: uint8)var u uint = 7 // uint (unsigned)var p float32 = 22.7 // 32-bit float
x := 5x++fmt.Println("x + 4 =", x + 4)fmt.Println("x * 4 =", x * 4)
参见:更多操作符
isTrue := trueisFalse := false
fmt.Println(true && true) // true fmt.Println(true && false) // falsefmt.Println(true || true) // truefmt.Println(true || false) // truefmt.Println(!true) // false
参见:更多操作符
┌────┬────┬────┬────┬─────┬─────┐| 2 | 3 | 5 | 7 | 11 | 13 |└────┴────┴────┴────┴─────┴─────┘ 0 1 2 3 4 5
primes := [...]int{2, 3, 5, 7, 11, 13}fmt.Println(len(primes)) // => 6// 输出:[2 3 5 7 11 13]fmt.Println(primes)// 与 [:3] 相同,输出:[2 3 5]fmt.Println(primes[0:3])
var a [2]stringa[0] = "Hello"a[1] = "World"fmt.Println(a[0], a[1]) //=> Hello Worldfmt.Println(a) // => [Hello World]
var twoDimension [2][3]intfor i := 0; i < 2; i++ { for j := 0; j < 3; j++ { twoDimension[i][j] = i + j }}// => 2d: [[0 1 2] [1 2 3]]fmt.Println("2d: ", twoDimension)
func main () { b := *getPointer() fmt.Println("Value is", b)}func getPointer () (myPointer *int) { a := 234 return &a}a := new(int)*a = 234
参见:指针(Pointers)
s := make([]string, 3)s[0] = "a"s[1] = "b"s = append(s, "d")s = append(s, "e", "f")fmt.Println(s)fmt.Println(s[1])fmt.Println(len(s))fmt.Println(s[1:3])slice := []int{2, 3, 4}
另见:切片示例
const s string = "constant"const Phi = 1.618const n = 500000000const d = 3e20 / nfmt.Println(d)
i := 90f := float64(i)u := uint(i)// 将等于字符Zs := string(i)
i := 90// 需要导入“strconv”s := strconv.Itoa(i)fmt.Println(s) // Outputs: 90
package mainimport ( "fmt" s "strings")func main() { /* 需要将字符串导入为 s */ fmt.Println(s.Contains("test", "e")) /* 内置 */ fmt.Println(len("hello")) // => 5 // 输出: 101 fmt.Println("hello"[1]) // 输出: e fmt.Println(string("hello"[1]))}
package mainimport ( "fmt" "os")type point struct { x, y int}func main() { p := point{1, 2} fmt.Printf("%v\n", p) // => {1 2} fmt.Printf("%+v\n", p) // => {x:1 y:2} fmt.Printf("%#v\n", p) // => main.point{x:1, y:2} fmt.Printf("%T\n", p) // => main.point fmt.Printf("%t\n", true) // => TRUE fmt.Printf("%d\n", 123) // => 123 fmt.Printf("%b\n", 14) // => 1110 fmt.Printf("%c\n", 33) // => ! fmt.Printf("%x\n", 456) // => 1c8 fmt.Printf("%f\n", 78.9) // => 78.9 fmt.Printf("%e\n", 123400000.0) // => 1.23E+08 fmt.Printf("%E\n", 123400000.0) // => 1.23E+08 fmt.Printf("%s\n", "\"string\"") // => "string" fmt.Printf("%q\n", "\"string\"") // => "\"string\"" fmt.Printf("%x\n", "hex this") // => 6.86578E+15 fmt.Printf("%p\n", &p) // => 0xc00002c040 fmt.Printf("|%6d|%6d|\n", 12, 345) // => | 12| 345| fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45) // => | 1.20| 3.45| fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45) // => |1.20 |3.45 | fmt.Printf("|%6s|%6s|\n", "foo", "b") // => | foo| b| fmt.Printf("|%-6s|%-6s|\n", "foo", "b") // => |foo |b | s := fmt.Sprintf("a %s", "string") fmt.Println(s) fmt.Fprintf(os.Stderr, "an %s\n", "error")}
另见:fmt
Contains("test", "es") | true |
Count("test", "t") | 2 |
HasPrefix("test", "te") | true |
HasSuffix("test", "st") | true |
Index("test", "e") | 1 |
Join([]string{"a", "b"}, "-") | a-b |
Repeat("a", 5) | aaaaa |
Replace("foo", "o", "0", -1) | f00 |
Replace("foo", "o", "0", 1) | f0o |
Split("a-b-c-d-e", "-") | [a b c d e] |
ToLower("TEST") | test |
ToUpper("test") | TEST |
a := 10if a > 20 { fmt.Println(">")} else if a < 20 { fmt.Println("<")} else { fmt.Println("=")}
x := "hello go!"if count := len(x); count > 0 { fmt.Println("Yes")}
if _, err := doThing(); err != nil { fmt.Println("Uh oh")}
x := 42.0switch x { case 0: case 1, 2: fmt.Println("Multiple matches") case 42: // Don't "fall through". fmt.Println("reached") case 43: fmt.Println("Unreached") default: fmt.Println("Optional")}
参见:Switch
for i := 0; i <= 10; i++ { fmt.Println("i: ", i)}
nums := []int{2, 3, 4}sum := 0for _, num := range nums { sum += num}fmt.Println("sum:", sum)
i := 1for i <= 3 { fmt.Println(i) i++}
for i := 0; i <= 5; i++ { if i % 2 == 0 { continue } fmt.Println(i)}
for { fmt.Println("loop") break}
package mainimport ( "fmt")type Vertex struct { X int Y int}func main() { v := Vertex{1, 2} v.X = 4 fmt.Println(v.X, v.Y) // => 4 2}
参见:结构(Structs)
v := Vertex{X: 1, Y: 2}// Field names can be omittedv := Vertex{1, 2}// Y is implicitv := Vertex{X: 1}
您还可以输入字段名
m := make(map[string]int)m["k1"] = 7m["k2"] = 13fmt.Println(m) // => map[k1:7 k2:13]v1 := m["k1"]fmt.Println(v1) // => 7fmt.Println(len(m)) // => 2delete(m, "k2")fmt.Println(m) // => map[k1:7]_, prs := m["k2"]fmt.Println(prs) // => falsen := map[string]int{"foo": 1, "bar": 2}fmt.Println(n) // => map[bar:2 foo:1]
v := &Vertex{1, 2}v.X = 2
Doing v.X is the same as doing (*v).X, when v is a pointer.
func plus(a int, b int) int { return a + b}func plusPlus(a, b, c int) int { return a + b + c}fmt.Println(plus(1, 2))fmt.Println(plusPlus(1, 2, 3))
func vals() (int, int) { return 3, 7}a, b := vals()fmt.Println(a) // => 3fmt.Println(b) // => 7
r1, r2 := func() (string, string) { x := []string{"hello", "world"} return x[0], x[1]}()// => hello worldfmt.Println(r1, r2)
func split(sum int) (x, y int) { x = sum * 4 / 9 y = sum - x return}x, y := split(17)fmt.Println(x) // => 7fmt.Println(y) // => 10
func sum(nums ...int) { fmt.Print(nums, " ") total := 0 for _, num := range nums { total += num } fmt.Println(total)}sum(1, 2) //=> [1 2] 3sum(1, 2, 3) // => [1 2 3] 6nums := []int{1, 2, 3, 4}sum(nums...) // => [1 2 3 4] 10
import --> const --> var --> init()
var num = setNumber()func setNumber() int { return 42}func init() { num = 0}func main() { fmt.Println(num) // => 0}
func main() { // 将函数赋给名称 add := func(a, b int) int { return a + b } // 使用名称调用函数 fmt.Println(add(3, 4)) // => 7}
func scope() func() int{ outer_var := 2 foo := func() int {return outer_var} return foo}// Outpus: 2fmt.Println(scope()())
func outer() (func() int, int) { outer_var := 2 inner := func() int { outer_var += 99 return outer_var } inner() return inner, outer_var}inner, val := outer()fmt.Println(inner()) // => 200fmt.Println(val) // => 101
import "fmt"import "math/rand"
import ( "fmt" // 给 fmt.Println "math/rand" // 给 rand.Intn)
另见:导入
import r "math/rand"
import ( "fmt" r "math/rand")
r.Intn()
package main// 一个内部包只能被另一个包导入// 那是在以内部目录的父级为根的树内package internal
另见:内部包
// 以大写字母开头func Hello () { ···}
另见:导出的名称
package mainimport ( "fmt" "time")func f(from string) { for i := 0; i < 3; i++ { fmt.Println(from, ":", i) }}func main() { f("direct") go f("goroutine") go func(msg string) { fmt.Println(msg) }("going") time.Sleep(time.Second) fmt.Println("done")}
参见:Goroutines, Channels
package mainimport ( "fmt" "sync" "time")func w(id int, wg *sync.WaitGroup) { defer wg.Done() fmt.Printf("%d starting\n", id) time.Sleep(time.Second) fmt.Printf("%d done\n", id)}func main() { var wg sync.WaitGroup for i := 1; i <= 5; i++ { wg.Add(1) go w(i, &wg) } wg.Wait()}
参见:WaitGroup
ch <- 1ch <- 2ch <- 3close(ch) // 关闭频道
// 迭代通道直到关闭for i := range ch { ···}
// Closed if `ok == false`v, ok := <- ch
参见:范围和关闭
ch := make(chan int, 2)ch <- 1ch <- 2ch <- 3// 致命错误:// 所有 goroutine 都处于休眠状态 - 死锁
参见:缓冲通道
func main() { defer func() { fmt.Println("Done") }() fmt.Println("Working...")}
func main() { var d = int64(0) defer func(d *int64) { fmt.Printf("& %v Unix Sec\n", *d) }(&d) fmt.Print("Done ") d = time.Now().Unix()}
defer 函数使用当前值d,除非我们使用指针在 main 末尾获取最终值
func main() { defer fmt.Println("Done") fmt.Println("Working...")}
参见:Defer, panic and recover
type Vertex struct { X, Y float64}func (v Vertex) Abs() float64 { return math.Sqrt(v.X * v.X + v.Y * v.Y)}v := Vertex{1, 2}v.Abs()
参见:Methods
func (v *Vertex) Scale(f float64) { v.X = v.X * f v.Y = v.Y * f}v := Vertex{6, 12}v.Scale(0.5)// `v` 已更新
参见:指针接收器
type Shape interface { Area() float64 Perimeter() float64}
type Rectangle struct { Length, Width float64}
结构 Rectangle 通过实现其所有方法隐式实现接口 Shape
func (r Rectangle) Area() float64 { return r.Length * r.Width}func (r Rectangle) Perimeter() float64 { return 2 * (r.Length + r.Width)}
在 Shape 中定义的方法在Rectangle中实现
func main() { var r Shape = Rectangle{Length: 3, Width: 4} fmt.Printf("Type of r: %T, Area: %v, Perimeter: %v.", r, r.Area(), r.Perimeter())}
+ | & | += | &= | && | == | != | ( | ) |
- | | | -= | |= | || | < | <= | [ | ] |
* | ^ | *= | ^= | <- | > | >= | { | } |
/ | << | /= | <<= | ++ | = | := | , | ; |
% | >> | %= | >>= | -- | ! | ... | . | : |
&^ | &^= |