2017-10-28 2 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にチェックしましたが、正しい変換の使い方はまだ分かりません。

別の質問があります:

[]falseを返します前に、私は、型アサーション以来[100]int[]intを変更するには。

しかし、私はaの種類がわからない場合、どのように私は機能とスライス([]int)を返すようにinterface{}として配列(のような[99]int)を転送するタイプのアサーションを使用できますか?

+1

最初の例のタイプアサーションは、赤いニシンです。セマンティクスを変更せずに削除することができます。変数はその静的型を変更することはできません。 – Peter

答えて

2

最初にsrcを宣言したときは、fun1(src interface{})にタイプインタフェースの変数を作成しています。もちろん、lenを呼び出すことはできません。

理由はreflect.TypeOfは[] intと表記しています。なぜならTypeOfの仕組みによるものです。 インタフェース{}を取り、インタフェース{}内のオブジェクトのタイプを教えます

したがって、最初の例ではすでにインターフェイスが であり、2番目の例では、あなたの[] intスライスを保持するインスタンス。

0

Variablesからdynamic typeを引用:

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.

の最初の例では、srcdynamic typeを有しています。 srcの値は実行時にタイプ[]intとなりますが、最終的には宣言時にinterfaceタイプの&の動的タイプであるため、タイプはinterfaceになります。したがって、type assertionの間に変数srcを新しい変数に変更する必要があります。あなたは第二の例で行ったのと同様に

:あなたがエラーで終わるだろうとslice_src, _ := src.([]int)

あなたもsrc, _ := src.([]int)を行うことはできませんno new variables on left side of :=reflect.TypeOf()を使用して型スイッチ方法があり

0

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.

関連する問題