Go 学习笔记

69 阅读1分钟
  • high-performance
  • static-linked
  • built-in goroutine

Reference: www.w3schools.com/go/index.ph…

run

  • go run .\hello.go

build binary

  • go build .\helloworld.go
  • .\helloworld.go

ending style

  • ending a line (hitting the Enter key)
  • a semicolon ";"

variable definition

two way to define a var

package main
import ("fmt")
func main() {
  var student1 string = "John" //type is string
  var student2 = "Jane" //type is inferred
  x := 2 //type is inferred

  fmt.Println(student1)
  fmt.Println(student2)
  fmt.Println(x)
}

print

Go has three functions to output text:

Print()   // very basic 
Println() // add whitespace and white space
Printf()  // just like printf in c++

println is built-in function and will be removed eventually. fmt.println is standard library.

basic numeric

int Depends on platform: 32 bits in 32 bit systems and 64 bit in 64 bit systems

array

fixed length

var array_name = [length]datatype{values} // here length is defined
var array_name = [...]datatype{values} // here length is inferred

slice

dynamic length

slice_name := []datatype{values}

map

To declare a structure in Go, use the type and struct keywords:

type struct_name struct {
  member1 datatype;
  member2 datatype;
  member3 datatype;
  ...
}

argument pass

  • basic: pass by value(numeric, string...)
  • complex: pass by pointer(map, slice, channel)
  • there in no reference pass(literally) but pointer pass in Go lang

channel

package main

import "fmt"

func sum(s []int, c chan int) {
	sum := 0
	for _, v := range s {
		sum += v
	}
	c <- sum // send sum to c
}

func main() {
	s := []int{7, 2, 8, -9, 4, 0}

	c := make(chan int)
	go sum(s[:len(s)/2], c)
	go sum(s[len(s)/2:], c)
	x, y := <-c, <-c // receive from c

	fmt.Println(x, y, x+y)
}
  • By default, send and receive will block, without locks or cv

make vs new

  • new return T*, which is a pointer
  • make return T, which is only used for (slice, channel and map)
new(int)
new(Point)
&Point{}
&Point{2, 3}  // Combines allocation and initialization

var m map[string]int;
m = make(map[string]int);

import package

  • the exported function must start with uppercase
  • package is same to directory in some degree, the files in a folder should be in the same package
  • import "folder_path" is not a package but a folder name, but in most cases we make them identical.
  • import str "strings" can give a alias name