UTF-16
的code unit
,也就是两个字节,字符串是UTF-16 code unit
的序列,因此每个字符都是定长的,要想获得某个位置字符,很容易计算出它的字节在字符串中的位置。UTF-8
作为字符串的内部编码,因此对于大部分字符串都是ascii字符的情况下,占用的内存空间就会大大减少,但是带来的问题是,从字符串的字节slice中查找第n个字符比较麻烦,因为不能直接的计算出来。Go中用rune表示字符。var r rune = '文'
fmt.Printf("%#U\n", r)
//通过range可以遍历一个字符串中所有的rune:
const nihongo = "one world世界大同"
for index, runeValue := range nihongo {
fmt.Printf("%#U starts at byte position %d\n", runeValue, index)
}
//因为字符串是以UTF-8编码的,通过输出可以看到ascii字母只用一个字节,而这几个中文汉字每个汉字用了3个字节。
//要想获得字符串中包含几个字符(rune),下面的方法是不对的,它返回的是字符处内部的字slice的长度((9 + 4*3 =21):
const str = "one world世界大同"
fmt.Println(len(str))
var vs = "hello xiaoxiao"
const s = vs //错误!!
var v1 int = i
var v2 float32 = i
var v3 complex64 = i
type MyFile struct {
var F *os.File
}
func main() {
var mf MyFile
//错误!!!
mf.F, err := os.Open("dive-into-go.pdf")
fmt.Println(f, err)
}
var x interface{
} // x 为零值 nil,静态类型为 interface{}
var v *T // v 为零值 nil, 静态类型为 *T
x = 42 // x 的值为 42,动态类型为int, 静态类型为interface{}
x = v // x 的值为 (*T)(nil), 动态类型为 *T, 静态类型为 *T
// x1 x2 类型相同
// y y2 类型不同
var x struct{
I int }
type Foo struct{
I int }
var y Foo
var x2 struct{
I int }
type Bar struct{
I int }
var y2 Bar
x := [...]int{
1, 2, 3, 4, 5}
p := &x[0]
//p = p + 1
index2Pointer := unsafe.Pointer(uintptr(unsafe.Pointer(p)) + unsafe.Sizeof(x[0]))
p = (*int)(index2Pointer) //x[1]
fmt.Printf("%d\n", *p) //2
type ArbitraryType int // shorthand for an arbitrary Go type; it is not a real type
type Pointer *ArbitraryType
Pointer代表指向任意类型的指针,它有四个独有的操作:
switch x := f(); x>0 {
case true:
.....
}
var a []int
var c, c1, c2, c3, c4 chan int
var i1, i2 int
select {
case i1 = <-c1:
print("received ", i1, " from c1\n")
case c2 <- i2:
print("sent ", i2, " to c2\n")
case i3, ok := (<-c3): // same as: i3, ok := <-c3
if ok {
print("received ", i3, " from c3\n")
} else {
print("c3 is closed\n")
}
case a[f()] = <-c4:
// same as:
// case t := <-c4
// a[f()] = t
default:
print("no communication\n")
}
for {
// send random sequence of bits to c
select {
case c <- 0: // note: no statement, no fallthrough, no folding of cases
case c <- 1:
}
}
select {
} // block forever
c1 := make(chan string, 1)
go func() {
time.Sleep(time.Second * 2)
c1 <- "result 1"
}()
//执行超时case
select {
case res := <-c1:
fmt.Println(res)
case <-time.After(time.Second * 1):
fmt.Println("timeout 1")
}
//执行C2
c2 := make(chan string, 1)
go func() {
time.Sleep(time.Second * 2)
c2 <- "result 2"
}()
select {
case res := <-c2:
fmt.Println(res)
case <-time.After(time.Second * 3):
fmt.Println("timeout 2")
}