在golang中给map赋值

huangapple go评论91阅读模式
英文:

Assigning to map in golang

问题

在下面的Go代码片段中,我做错了什么?

type Element interface{}

func buncode(in *os.File) (e Element) {
    <snip>
    e = make(map[string]interface{})
    for {
        var k string = buncode(in).(string)
        v := buncode(in)
        e[k] = v
    }
    <snip>
}

编译时给出了以下错误:

gopirate.go:38: invalid operation: e[k] (index of type Element)

Double ewe T eff?

在这段代码中,你的错误是将e声明为Element类型,而不是具体的map[string]interface{}类型。Element是一个接口类型,不能直接用于索引操作。你需要将e的类型更改为map[string]interface{},以便能够正确地进行索引操作。

英文:

In the following go snippet, what am I doing wrong?

type Element interface{}

func buncode(in *os.File) (e Element) {
    &lt;snip&gt;
    e = make(map[string]interface{})
    for {
        var k string = buncode(in).(string)
        v := buncode(in)
        e[k] = v
    }
    &lt;snip&gt;
}

Compiling gives me this error:

gopirate.go:38: invalid operation: e[k] (index of type Element)

Double ewe T eff?

答案1

得分: 3

buncode函数中,你声明了e Element,其中type e Element interface{}。变量e是一个标量值,你试图对其进行索引。

类型

变量的静态类型(或者只是类型)是由其声明定义的类型。接口类型的变量也有一个独特的动态类型,它是变量在运行时存储的实际类型。动态类型可能在执行过程中变化,但始终可以赋值给接口变量的静态类型。对于非接口类型,动态类型始终是静态类型。

e的静态类型是Element,是一个标量。e的动态类型是map[string]interface{}

这是你代码的修订版,可以编译通过。

type Element interface{}

func buncode(in *os.File) (e Element) {
    m := make(map[string]interface{})
    for {
        var k string = buncode(in).(string)
        v := buncode(in)
        m[k] = v
    }
    return m
}

为什么你要对buncode进行递归调用?

英文:

In the buncode function you declare e Element, where type e Element interface{}. The variable e is a scalar value, which you are trying to index.

> Types
>
> The static type (or just type) of a variable is the type defined by
> its declaration. Variables of interface type also have a distinct
> dynamic type, which is the actual type of the value stored in the
> variable at run-time. The dynamic type may vary during execution but
> is always assignable to the static type of the interface variable. For
> non-interface types, the dynamic type is always the static type.

The static type of e is Element, a scalar. The dynamic type of e is map[string]interface{}.

Here's a revised, compilable version of your code.

type Element interface{}

func buncode(in *os.File) (e Element) {
    m := make(map[string]interface{})
    for {
        var k string = buncode(in).(string)
        v := buncode(in)
        m[k] = v
    }
    return m
}

Why are you making the recursive calls to buncode?

huangapple
  • 本文由 发表于 2011年8月12日 21:37:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/7040861.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定