2017-10-28 18 views
-2

我尝试:转换阵列接口{}切片,但结果不能使用LEN()和其他方法

var a [100]int 
func fun1(src interface{}) interface{} { 
    src, _ = src.([100]int) // changed []int to [100]int 
    fmt.Println(reflect.TypeOf(src)) // result: []int 
    dest := make([]int, len(src)) 
    return dest 
} 

有一个错误:

message: 'invalid argument src (type interface {}) for len' 

但是,如果我重新定义一个变量:

var a [100]int 
func fun1(src interface{}) interface{} { 
    slice_src, _ := src.([100]int) //changed []int to [100]int 
    fmt.Println(reflect.TypeOf(slice_src)) // result: []int 
    dest := make([]int, len(slice_src)) 
    return dest 
} 

它会没事的。

为什么reflect.TypeOf(src)会在我使用src.([]int)后打印[] int,但错误显示src仍然是接口{}? 我检查了这个convert interface{} to int,但我仍然不明白如何使用正确的转换。

还有另外一个问题:

我改变了[]int[100]int因为类型声明之前将返回[]false

但是,如果我不知道的a类型,我该如何使用类型断言来传递一个数组(如[99]int)作为interface{}工作并返回片([]int)?

+1

第一个示例中的断言类型是红色鲱鱼。您可以在不更改语义的情况下将其删除。一个变量不能改变它的静态类型。 – Peter

回答

2

当你第一次声明src,在fun1(src interface{})你正在做一个类型接口的变量。其中,当然不能有len对它进行调用。

原因reflect.TypeOf说[] int是由于TypeOf的工作原理。 它需要的接口{},并告诉你的东西类型的接口{}

所以,在第一个例子中,你已经有了一个接口 ,并在第二个例子中,去自动创建的接口{}实例来保存你的[] int切片。

0

引用dynamic typeVariables

The static type (or just type) of a variable is the type given in its declaration, the type provided in the new call or composite literal, or the type of an element of a structured variable. Variables of interface type also have a distinct dynamic type, which is the concrete type of the value assigned to the variable at run time (unless the value is the predeclared identifier nil, which has no type). The dynamic type may vary during execution but values stored in interface variables are always assignable to the static type of the variable.

在第一示例中,src具有dynamic type。执行期间src的值将为[]int,但最终类型将为interface,因为它是动态类型&它在声明时是interface类型。因此,您需要在type assertion期间将变量src更改为新变量。

你在第二个例子中所做的类似:slice_src, _ := src.([]int)

你甚至不能做src, _ := src.([]int),你将结束与错误no new variables on left side of :=

0

有使用reflect.TypeOf()一种开关方法:golang type assertion using reflect.Typeof()How to get the reflect.Type of an interface?

报价How to get the reflect.Type of an interface?

You can't. Type assertions allow you to take advantage of the static type checking that the language gives you even if you have an interface, whose type isn't statically checked. It basically works something like this:

You have some statically typed variable s, which has type t. The compiler enforces the guarantee that s always has type t by refusing to compile if you ever try to use s as if it were a different type, since that would break the guarantee.