注意: 切片必须要初始化 才能使用 ,切片是引用类型
a :=[]int{} // 这上叫始化 此时并没有申请内存 // 如果要追加值的话: append
ints := append(a, 1, 2, 3)
a := make([]int,5)
// 声明切片类型
var a []string //声明一个字符串切片
var b = []int{} //声明一个整型切片并初始化
var c = []bool{false, true} //声明一个布尔切片并初始化
var d = []bool{false, true} //声明一个布尔切片并初始化
fmt.Println(a) //[]
fmt.Println(b) //[]
fmt.Println(c) //[false true]
fmt.Println(a == nil) //true
fmt.Println(b == nil) //false
fmt.Println(c == nil) //false
// fmt.Println(c == d) //切片是引用类型,不支持直接比较,只能和nil比较
两个切片追加 需要用到 ...
s1 := []int{1, 2, 3}
s2 := []int{4, 5, 6}
//把s2 切片追加到 s1切片中去
appendStr := append(s1, s2...)
fmt.Println(appendStr)
注意如果是不同类型的切片: 可以用 interface 类型
package main
import (
"fmt"
)
type Data struct {
Value interface{} // 使用空接口来存储任意类型的数据
}
func main() {
var dataSlice []Data
dataSlice = append(dataSlice, Data{Value: 1}) // 追加 int 类型
dataSlice = append(dataSlice, Data{Value: "hello"}) // 追加 string 类型
dataSlice = append(dataSlice, Data{Value: 3.14}) // 追加 float64 类型
for _, data := range dataSlice {
fmt.Println(data.Value)
}
}
类型断言的应用
下面是如何定义一个可以包含字符串和数字的切片的示例:
package main
import (
"fmt"
)
func main() {
// 创建一个可以包含任意类型数据的切片
var mixedSlice []interface{}
// 向切片中添加字符串
mixedSlice = append(mixedSlice, "Hello")
// 向切片中添加数字
mixedSlice = append(mixedSlice, 42)
// 添加更多的数据类型
mixedSlice = append(mixedSlice, true) // 布尔值
mixedSlice = append(mixedSlice, 3.14) // 浮点数
// 打印切片内容
for _, value := range mixedSlice {
fmt.Println(value)
}
}
在这个例子中,mixedSlice
是一个 []interface{}
类型的切片,它可以存储任何类型的值。当你想要访问切片中的具体值时,你需要将它们断言(type assertion)回原始类型,例如:
for _, value := range mixedSlice {
switch v := value.(type) {
case string:
fmt.Println("String:", v)
case int:
fmt.Println("Int:", v)
case bool:
fmt.Println("Bool:", v)
case float64:
fmt.Println("Float64:", v)
default:
fmt.Println("Unknown type")
}
}
这样,你就可以根据实际存储在切片中的数据类型来处理它们了。使用空接口和类型断言是处理这种“混合”类型切片的有效方式。