Go foundation

2018-10-24  本文已影响0人  曹小恒

variable definition

basic method:

var variableName typevar person string

multiple variable definition:

var vname1, vname2, vname3 type

define the variable and initialize it:

var variableName type = value

initialize multiple variables:

var vname1, vname2, vname3 type = v1, v2, v3

or simplify it:

var vname1, vname2, vname3 = v1, v2, v3

or do the most simplified one:

vname1, vname2, vname3 := v1, v2, v3

Noted that this version should only be adopted inside the functions, or the complation will fail.

So the definition withe the prefix var can be used for the global variables.

_ is a special variable name, all values allocated to it will be deprecated

_, b := 34, 35

Declared but not used variables will trigger mistakes, which is not permmited in go.

Const

Const are those whose values have been determined when compiling.

const constantName = value//if necessary, allocate the type of the constconst Pi float32 = 3.1415926const prefix = "astaxie_"

Other types

Boolean, int, uint, int8, int16, int32, int64, byte, uint8, uint16, uint32, uint64, float32, float64

var c complex64 = 5+5ifmt.Printf("Value is: %v",c)

String

Use ""or to define the String in between.

var frenchHello stringvar emptyString string = ""func test(){    no, yes, maybe := "no", "yes", "maybe"    japaneseHello := "Konichiwa"    frenchHello := "Bonjour"}

Noted that string is not changable

var s string = "hello"s[0] = 'c'//raise mistake "cannot assign to s[0]"

here is the method to do the modification

s := "hello"c := []byte(s) //convert s to []bytec[0] = 'c's2 := string(c) //convert it back

Or use slice to modify the string

s := "hello"h := "c" + s[1:]fmt.Printf("%s\n",h)

+ can connect two strings together

s := "hello"h := "world"a := s+hfmt.Printf("%s\n",a)

can preserve the initial format of the string, all things will remain the same.

m := `Hello        World`fmt.Printf("%s\n",m)

Here is the output:

Hello    World

Error

The type of error is specially for handling mistakes. There us a package of errors.

err := errors.New("emit macho dwarf: elf header corrupted")if err != nil{    fmt.Printf(err)}

Storage of data

[图片上传失败...(image-c53635-1540311861796)]

Some skills

import(    "fmt"    "os")const(    i = 100    pi = 3.1415    prefix = "Go_")var (    i int    pi float32    prefix string)

One more lines of const, one more the value of iota

package mainimport (    "fmt")const (    x = iota //x = 0    y = iota //y = 1    z //z = 2, with omission declaration)const v = iota //one more keyword const, reset the value of iotaconst (    h,j,i = iota,iota,iota //all is 0, three should match three)const (    a = iota    //a = 0    b = "B"    c,d,e = iota  //c,d,e = 1)

Default rules

array

Declaration

var arr [n]type

n is the length of the array, type is the elements this array stores,

var arr [10]intarr[0] = 42arr[1] = 13fmt.Println(arr[9]) //The initial value of a[9] is 0

Declaration inside the functions:

a := [3]int{1,2,3}b := [10]int{1,2,3}c := [...]int{4,5,6} //omit the length, count the number of elements instead

Matraix:

doubleArray := [2][4]int{    {1,2,3,4}    {5,6,7,8}}

Noted that when we pass one array into the function, we pass the copy of this array rather than its pointer.

if you wanted to modify the elements anyway, use slice.

Slice

Or could be described as "dynamical array", do not need the specification of length.

var fslice []int

Initialization:

slice := []byte {'a','b','c'}

slice could be picked from an existed array by array[i:j], array[i] is included, array[j] is excluded, the length is j-i

var ar = [10]int {1,2,3,4,5,6,7,8,9,10}var a, b []inta = ar[2,5]b = ar[3,5]

[图片上传失败...(image-229275-1540311861796)]

When changing the values in the slice, the corresponding value in the array will be changed,too.

The interfaces in slice:

[图片上传失败...(image-b74cc1-1540311861796)]

capacity could be specified now:

slice = array[2:4:7] //capacity is 7-2

map

The dictionary in Python, whose index could be many types besides int.

Noted that the declaration should be outside the function, while the memory allocation should be inside the function.

var numbers map[string]int //declaration, should initialize it by make afterwardsnumbers = make(map[string]int)numbers["one"] = 1numbers["two"] = 2
rating := map[string]float32{"C":5,"Go":4.5,"Python":4.5}csharpRating, ok := rating["C#"]if ok{    fmt.Println("C# is in the map and its rating is ", cssharpRating)}delete(rating, "C#")

Differences between make and new

Zero values

int     0int8    0int32   0int64   0uint    0x0rune    0 //rune的实际类型是 int32byte    0x0 // byte的实际类型是 uint8float32 0 //长度为 4 bytefloat64 0 //长度为 8 bytebool    falsestring  ""

The default padding values when you new the type

上一篇下一篇

猜你喜欢

热点阅读