为什么结构的字段是“非名称"字段? [英] Why is a struct's field a "non-name"

查看:42
本文介绍了为什么结构的字段是“非名称"字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码不起作用.它抱怨j.Bar是一个非名称":

This code does not work. It complains that j.Bar is a "non-name":

package main

import "fmt"
import "os"

type foo struct {
    Bar string
    Baz int
}

func main() {
    var j foo

    // this next line fails with "non-name j.Bar on left side of :="
    j.Bar, ok := os.LookupEnv("SOME VAR")
    if ( ! ok ) {
        panic("lookup failed!")
    }
    fmt.Printf("j.Bar is now %s\n",j.Bar)
}

现在,我可以轻松更改它以使其正常工作:

Now I can change it easily to work:

package main

import "fmt"
import "os"

type foo struct {
    Bar string
    Baz int
}

func main() {
    var j foo

    val, ok := os.LookupEnv("SOME VAR")
    if ( ! ok ) {
        panic("lookup failed!")
    }
    j.Bar = val
    fmt.Printf("j.Bar is now %s\n",j.Bar)
}

我真的为非名字"错误感到困惑.j.Bar是一个字符串. os.LookupEnv()返回字符串作为其第一个值.那么采用字符串并将其放入字符串变量中会出现什么问题?

I'm really puzzled by the "non-name" error. j.Bar is a string. os.LookupEnv() returns a string as its first value. So what is the problem with taking a string and putting it into a string variable?

推荐答案

:= 运算符同时声明一个新变量,并为其分配值. j.Bar 在Go中不是合法的变量名称;变量名称不能包含句点.现在,显然,您正在尝试将一个值分配给struct字段,而不是为其名称加上句点的变量(编译器只是不知道).您可以只使用赋值而无需声明:

The := operator simultaneously declares a new variable, and assigns a value to it. j.Bar is not a legal variable name in Go; variable names cannot contain periods. Now, obviously you're trying to assign a value to a struct field, not a variable with a period in its name (the compiler just doesn't know it). You can do this, using just assignment without declaration:

var ok bool
j.Bar, ok = os.LookupEnv("SOME VAR")

或者这样,一次声明两个变量:

Or this, declaring two variables at once:

bar,ok := os.LookupEnv("SOME VAR")
if ok {
    j.Bar = bar
}

另请参见:浏览简短的变量声明 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆