英文:
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) {
<snip>
e = make(map[string]interface{})
for {
var k string = buncode(in).(string)
v := buncode(in)
e[k] = v
}
<snip>
}
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
?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论