简体   繁体   English

为什么 [capacity]string assert to []string 在 Golang 中会失败?

[英]Why [capacity]string assert to []string will be failed in Golang?

I am using Golang1.14.我正在使用 Golang1.14。

Here is the test code.这是测试代码。

package main

import "time"

func checkData(data interface{}) {
    if _, ok := data.([]string); ok {
        println("Assert true.")
    } else {
        println("Assert false.")
    }
}

func main() {
    var years [20]string
    for i := 0; i < 20; i++ {
        years[i] = string(time.Now().Year() - 10 + i)
    }
    checkData(years)

    foods := []string{"Fruit", "Grass", "Fish", "Meat"}
    checkData(foods)
}

The output is:输出是:

Assert false.
Assert true.

I am new to Golang and really confusing that [20]string is not a []string .Can someone tell me why?Thanks.我是 Golang 的新手,真的很困惑[20]string不是[]string 。有人能告诉我为什么吗?谢谢。

[20]string is an array. [20]string是一个数组。 It is a type that contains 20 strings, and if you pass it as an interface{}, you can recover it using intf.([20]string) .它是一种包含 20 个字符串的类型,如果将其作为 interface{} 传递,则可以使用intf.([20]string)恢复它。

[]string is a slice. []string是一个切片。 It has a backing array, but it is essentially a view over an array.它有一个支持数组,但它本质上是一个数组视图。 You assertion checks if the interface is a slice, so this one works.你断言检查接口是否是一个切片,所以这个工作。

Arrays and slices are different things in Go.数组和切片在 Go 中是不同的东西。 An array is a data type with a fixed size.数组是具有固定大小的数据类型。 For instance:例如:

func f(arr [10]int) {...}

You can only call f with an int array of size 10. When you do call it, the array will be passes as value, so the function will get a copy of the array, all 10 members of it.您只能使用大小为 10 的 int 数组调用f 。当您调用它时,该数组将作为值传递,因此该函数将获得该数组的副本,包括它的所有 10 个成员。 But:但:

func f(arr []int) {...}

You can call f with any size of slice.您可以使用任何大小的切片调用f A slice contains a reference to its underlying array, so an array copy will not take place here.切片包含对其底层数组的引用,因此此处不会发生数组复制。 You cannot call this f` with an array.你不能用数组调用this f`。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM