GO-Channel篇

1.⻓度为0的数组在内存中并不占⽤空间。空数组虽然很少直接使⽤,但是可以⽤于强调某种特有类型的

操作时避免分配额外的内存空间,⽐如⽤于管道的同步操作:
c1 := make(chan [0]int)
go func() {
fmt.Println("c1")
c1 <- [0]int{}
}()
<-c1

在这⾥,我们并不关⼼管道中传输数据的真实类型,其中管道接收和发送操作只是⽤于消息的同步。
对于这种场景,我们⽤空数组来作为管道类型可以减少管道元素赋值时的开销。当然⼀般更倾向于⽤
⽆类型的匿名结构体代替:
c2 := make(chan struct{})
go func() {
fmt.Println("c2")
c2 <- struct{}{} // struct{}部分是类型, {}表示对应的结构体值
}()
<-c2

2.字符

字符串的元素不可修改,是⼀个只读的字节数组,

example:

func main() {
//查询Unicode字符串长度用utf8.RuneCountInString()函数,ASCII字符用len()
str1:="君のことが大好きです、"
str2:="这是中文"
n1:=utf8.RuneCountInString(str1)
n2:=utf8.RuneCountInString(str2)
fmt.Println(n1,n2)
//bianli_ASCII()//乱码了,
bianli_Unicode()
  
  
  for i, c := range []byte("世界abc") {
   fmt.Println(i, c)//仅能成功遍历ascii码
  }
}
func bianli_ASCII(){
theme:="狙击 start"
for i:=0;i<len(theme);i++{
fmt.Printf("ASCII: %c %d\n",theme[i],theme[i])
}
}
func bianli_Unicode(){
theme:="狙击 start"
for _,s:=range theme{
fmt.Printf("Unicode: %c %d\n",s,s)
}
}


猜你喜欢

转载自www.cnblogs.com/wddx5/p/12288527.html