for range 循环的副本switch 中的 case 语句常量(表达式值)不可以重复
上代码, 自己品
package main import "fmt" func main() { list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} for i := range list { if i == 3 { list[i] |= i } } fmt.Println(list) // [1 2 3 7 5 6 7 8 9] }
package main import "fmt" func main() { list := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9} // 数组 maxIndex := len(list) - 1 for i, ele := range list { // 循环的是数组的副本, ele是副本的 fmt.Println(list[i], ele) if i == maxIndex { list[0] += ele } else { list[i+1] += ele } } fmt.Println(list) // [10 3 5 7 9 11 13 15 17] }
package main import "fmt" func main() { list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} // 切片 maxIndex := len(list) - 1 for i, ele := range list { // 循环的是切片的副本, 切面是引用类型, 所以是指针的副本, ele是最新的 fmt.Println(list[i], ele) if i == maxIndex { list[0] += ele } else { list[i+1] += ele } } fmt.Println(list) // [46 3 6 10 15 21 28 36 45] }
package main import "fmt" func main() { list := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9} // 数组 //list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} // 切片 switch 1 + 3 { case list[0], list[1]: fmt.Println("0 or 1") case list[2], list[3]: fmt.Println("2 or 3") case list[4], list[5]: fmt.Println("4 or 5") } // 2 or 3 }
package main import "fmt" func main() { list := [...]int8{1, 2, 3, 4, 5, 6, 7, 8, 9} // 数组 //list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} // 切片 switch 2 { // int case list[0]: // in8, 编译错误: invalid case list[0] in switch on 2 (mismatched types int8 and int) fmt.Println("0") case list[1]: fmt.Println("1") case list[2]: fmt.Println("2") } //编译错误 }
package main import "fmt" func main() { list := [...]int8{1, 2, 3, 4, 5, 6, 7, 8, 9} // 数组 //list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} // 切片 switch list[0] { // int8 case 0: // int, 会转换成 int8 fmt.Println("0") case 1: fmt.Println("1") case 2: fmt.Println("2") } // 1 }
package main import "fmt" func main() { list := [...]int8{1, 2, 3, 4, 5, 6, 7, 8, 9} // 数组 //list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} // 切片 switch list[0] { // int8 case 0: fmt.Println("0") case 1: fmt.Println("1") case 2: fmt.Println("2") case 0: //编译错误: duplicate case 0 in switch. case语句表达式的结果值不能重复. 只有常量才会 fmt.Println("0(2)") case 5 - 5: //编译错误: duplicate case 5 - 5 (value 0) in switch fmt.Println("0(5-5)") } }
package main import "fmt" func main() { list := [...]int8{1, 2, 3, 4, 5, 6, 7, 8, 9} // 数组 //list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} // 切片 switch list[0] { // int8 case list[0]: // int, 会转换成 int8 fmt.Println("0") case list[1]: fmt.Println("1") case list[0], list[2]: fmt.Println("2") case list[0]: fmt.Println("0") } // 0 }
package main import "fmt" func main() { list := interface{}(byte(127)) switch t := list.(type) { case uint8, uint16: fmt.Println("uint8 or uint16") case byte: // 编译错误duplicate case byte in type switch. type byte = uint8 fmt.Println("byte") default: fmt.Println("未知类型", t) } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)