如何在多重赋值语句中给结构体字段变量赋值

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

How Do You Assign A Struct Field Variable In Multiple Assignment Statement

问题

如何在多重赋值语句中为结构体字段变量赋值?请参考下面的代码。

type TestMultipleReturns struct {
    value string
}

func (t *TestMultipleReturns) TestSomething() {
    someMap := make(map[string]string)
    someMap["Test"] = "world"
    t.value, exists := someMap["doesnotexist"] // 失败

    // 可行,但是否真的需要第二行?
    tmp, exists := someMap["doesnotexist"]
    t.value = tmp

    if exists == false {
        fmt.Println("t.value未设置。")
    } else {
        fmt.Println(t.value)
    }
}

在上述代码中,t.value, exists := someMap["doesnotexist"] 这行代码会导致编译错误。为了解决这个问题,你可以使用一个额外的变量来接收 someMap["doesnotexist"] 的值,然后将其赋给 t.value。这样,你就可以避免编译错误。

希望对你有帮助!如果你有任何其他问题,请随时提问。

英文:

How do you assign a struct field variable in a multiple assignment statement? Please refer to code below.

type TestMultipleReturns struct {
	value string
}

func (t *TestMultipleReturns) TestSomething() {
	someMap := make(map[string]string)
	someMap["Test"] = "world"
	t.value, exists := someMap["doesnotexist"] // fails

    // works, but do I really need a 2nd line?
    tmp, exists := someMap["doesnotexist"] 
    t.value = tmp

	if exists == false {
		fmt.Println("t.value is not set.")
	} else {
		fmt.Println(t.value)
	}
}

答案1

得分: 6

短变量声明 不支持分配结构体接收器属性;它们在规范定义中被省略:

与常规变量声明不同,短变量声明可以重新声明变量,前提是它们最初在同一代码块(或函数体的参数列表)中以相同的类型进行了声明,并且至少有一个非空白变量是新的。

修复方法是在赋值之前定义exists,并且不使用短变量声明:

type TestMultipleReturns struct {
    value string
}

func (t *TestMultipleReturns) TestSomething() {
    someMap := make(map[string]string)
    someMap["Test"] = "world"
    var exists bool
    t.value, exists = someMap["doesnotexist"]

    if exists == false {
        fmt.Println("t.value is not set.")
    } else {
        fmt.Println(t.value)
    }
}
英文:

Short variable declaration do not support assigning struct receiver properties; they are omitted from the spec definition:

> Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new.

The fix is to define exists before the assignment and not use short variable declarations:

type TestMultipleReturns struct {
    value string
}

func (t *TestMultipleReturns) TestSomething() {
    someMap := make(map[string]string)
    someMap["Test"] = "world"
    var exists bool
    t.value, exists = someMap["doesnotexist"]

    if exists == false {
        fmt.Println("t.value is not set.")
    } else {
        fmt.Println(t.value)
    }
}

huangapple
  • 本文由 发表于 2016年11月30日 01:42:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/40872306.html
匿名

发表评论

匿名网友

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

确定