Imports can also be in multiple import statements.
import"fmt"import"math"
Exported names
fmt.Println(math.pi) // cannot refer to unexported name math.pifmt.Println(math.Pi) // 3.141592653589793
When importing a package, you can only accessible to its Exported names. Which begins with a capital letter i.e., Pi
Functions
// Basicfuncadd(x int, y int) int {return x + y}// You can omit the type if function parameters has same typefuncadd(x, y int) { ... }// Multiple result// Simply exchange the positions of x and yfuncswap(x, y string) (string, string) {return y, x}funcmain() { a, b :=swap("world", "hello") fmt.Println(a, b) // "Hello World"}// Named return valuesfuncsplit(sum int) (x, y int) { x = sum *4/9 y = sum - xreturn}funcmain() { fmt.Println(split(17)) // 7 10}
Variables
// A var statement can be at package or function levelvar i, j boolvar some_var // don't use underscore in Go names; var some_var should be someVarfuncmain() {var i int}// Variables with initializersvar i, j int=1, 2// Short variable declarations// := construct is not available outside a functionk :=3
Basic types
// Variable declaration can be "factored" into blocks like thisvar ( ToBe bool=false MaxInt uint=1<<64-1 z complex128= cmplx.Sqrt(-5+12i))
Zero value
Variables declared without an explicit value are given intial value. this is called zerovalue.
var i intvar f float64var b boolvar s stringfmt.Printf("%v%v%v%q\n", i, f, b, s)// 0 0 false ""
Type conversions
The expression T(v) converts the value v to the type T.
var x =3var y float64= math.Sqrt(float64(x))var z float64= math.Sqrt(x) // cannot use x as typeof float64..
Type inference
The variable's type is inferred from the value on the right hand side.
i :=3// becomes intf :=3.14// becomes float64g :=0.993+0.5i// becomes complexx128
Constants
Constant cannot be declared using := syntax.
const World ="世界"// Numeric Constants (high-precision values)const ( Big =1<<100)