这篇集中记录一些基本知识,权当笔记。
小知识点
字符串操作
1 | // 取字符串前7个 |
内置关键字
内置函数
- len、cap len用于返回某个类型的长度或数量(字符串、数组、切片、map、管道);cap用于返回某个类型的最大容量(只可用于切片和map)
- new、make new和make都用于内存分配:new用于值类型和用户定义的类型,make用于内置类型(切片、map、管道)
- copy、append copy用于复制切片;append用于连接切片
- panic、recover 两者均用于错误处理机制;panic类似于C语言中的perror
- print、println 底层打印函数
- complex、read、imag complex用于创建复数;read用于提出复数的实部;imag用于提取复数的虚部
杂记
反引号保持原有字符串含义,不进行转义。如\n
等。可定义多行字符串——包括在Printf中。但是,需要顶格编写,否则会有过多空格。
遇到的问题及解决
1 | cannot use array["foo"] (type interface {}) as type uint8 in argument to getType: need type assertion |
原因及解决:
array是intergace{},即使其中的值已经是uint8,亦提示。添加强制转换对应的类型即可。
1 | ret := getType(array["foo"].(uint8)); // 最后的.(uint8) |
类型转换:
- 各类型之间无法直接赋值(即使底层类型一样),如uint32参数无法传递到int,需要用int(foo)转换。
- 超出范围将截取。
int(buf.ReadUint16()) * 600;
需要先转为int,否则结果不对
1 | go build command-line-arguments: build output "foobar" already exists and is not an object file |
原因及解决:
foobar被改为其它文件(如源码文件),删除重新编译即可。
1 | use of package strings without selector |
将strings包名,误作为参数。
1 | mismatched types int and time.Duration) |
原因及解决:time.Sleep(myTime*time.Second)
, myTime 是int转换,而Sleep参数为Duration,如果直接传数字,如time.Sleep(5*time.Second)
是因为golang已经帮转换了。解决:time.Sleep(time.Duration(myTime)*time.Second)
。
疑问
有没有类似NodeJS字符串拼接方式?不管参数类型,直接用+
?
有没有类似NodeJS输出格式output ${dd} ${bb}
这样的格式?