Go foundation

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

  • rune is equivalent to int32, byte is equivalent to uint8.

  • int's lenth is 32, but it is not equal to int32.

  • No float, the deflaut one is float64

  • complex is supported, complex128(64+64i) and complex64(32+32i)

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

  • declaration by groups
import(    "fmt"    "os")const(    i = 100    pi = 3.1415    prefix = "Go_")var (    i int    pi float32    prefix string)
  • iota enumeration

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

  • variables with capital letter are public, other packages could read the value, variables with lowercase letters are private.

  • Same as the fuction names.

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)]

  • len can get the length

  • cap can get the capacity

  • append can add one or more elements and return the slice

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
  • map is unordered, which should be acquired by key rather than index

  • map has two return, the first one is the value, the second one is the boolean

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

  • make: allocate memory for map,slice,channel,return T type rather than *T.

  • new: allocate memory for various types, the default value is 0, return *T(its address) pointingto T's value

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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,711评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,079评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,194评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,089评论 1 286
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,197评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,306评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,338评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,119评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,541评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,846评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,014评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,694评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,322评论 3 318
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,026评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,257评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,863评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,895评论 2 351

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,317评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,444评论 0 23
  • 笔墨里的时光#9/30 读书《你的孤独虽败犹荣》 今天是鱼爸的生日,结婚已经12年了,给鱼爸过生日的次数少之又少。...
    柠檬草LF阅读 192评论 7 5
  • 刚落地哪知天降一块巨石,正好砸中了清风的双腿,剧烈的疼痛差点使他晕过去,但他知道机缘便在眼前,不能错过……强忍着疼...
    谪仙韩大人阅读 337评论 0 1
  • 这个月内学习了诸多教学上的东西,希望借助专家的指导快速提升自己的教学水准。专家很多,各自成体系,有理论有...
    一颗麦稻阅读 601评论 0 0