无法访问在另一个函数中更改的结构字段。

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

cannot access the struct field changed in another function

问题

我是Go语言的初学者。我在函数List中创建了一个结构体的对象数组,并将该对象数组的地址传递给另一个函数Changedlist。在Changedlist函数中,我将其作为指针接收。我想在Changedlist函数中编辑传递的数组对象的某些字段,并将其传回调用函数List。但是当我尝试在调用的函数中访问它时,无法访问Changedlist函数中的更新版本。

以下是我的代码:

type Mail struct {
    Name    string
    Address string
    Status  bool
    Error   error
}

func List() {
    var addressList = make([]Mail, 2)
    addressList[0].Name = "Name"
    addressList[0].Address = "Address"
    addressList[1].Name = "Name1"
    addressList[1].Address = "Address"
    newAddress := Changedlist(&addressList)
    fmt.Println(newAddress)
}

func Changedlist(addressList *[]Mail) *[]Mail {
    for _, r := range *addressList {
        if r.Name == "Name1" {
            r.Status = false
            r.Error = errors.New("Error in the name")
            continue
        }
        r.Status = true
        r.Error = nil
    }
    return addressList
}

我期望的是,当我在List函数中获取name时,status将变为true。但实际上它是false,这是bool的默认值。这意味着对实际的数组结构体没有进行更改,而是修改了副本。请问有人可以指导我如何实现这个目标吗?谢谢。

英文:

I m beginner in go lang. I have created an object array of a struct in function list and pass the address of that object array to another function changelist.In my function changelist i get it as pointer.I wanted to edit some of the fields of passed array object inside this function changedlist and pass it back to the called function list.When i try to access it in my called function i cant access the updated version from the changedlist function.

Here is my code
type Mail struct {
		Name    string
		Address string
		Status  bool
		Error   error
	}
function List(){
          var addressList = make([]Mail,2)
	      addressList[0].Name = "Name"
	      addressList[0].Address = "Address"
          addressList[1].Name = "Name1"
	      addressList[1].Address = "Address"
	      newAddress:=changedlist(&addressList)
          fmt.Println(newAddress)
}
function Changedlist(addressList *[]Mail)*[]Mail{
            for _,r:=range *addressList{
                    if r.Name=="Name1"{
                          r.Status=false
                           r.err=errors.New("Error in the name")
                            continue
                        }
                      r.Status=true
                      r.Error=nil
                 }
           return addressList
   }

Here what i was expecting is for name, the status will become true when i get this in my list function.But it is false which is the default value of the bool.This means that the changes are not done to the actual array struct.It is modifying the copied version.Can someone please point me in the right direction how to achieve this..Thanks.

答案1

得分: 0

package main

import (
	"errors"
	"fmt"
)

type Mail struct {
	Name    string
	Address string
	Status  bool
	Error   error
}

func List() {
	var addressList = make([]Mail, 2)
	addressList[0].Name = "Name"
	addressList[0].Address = "Address"
	addressList[1].Address = "Address"
	addressList[1].Name = "Name1"
	fmt.Println(addressList)
	newAddress := Changedlist(&addressList)
	fmt.Println(newAddress)
}

func Changedlist(addressList *[]Mail) *[]Mail {
	for k := range *addressList {
		if (*addressList)[k].Name == "Name1" {
			(*addressList)[k].Status = false
			(*addressList)[k].Error = errors.New("Error in the name")
			continue
		}
		(*addressList)[k].Status = true
		(*addressList)[k].Error = nil
	}
	return addressList
}

func main() {
	List()
}

这是我的代码,虽然不完美但是可以正常工作。

你有一些错误:

  1. "function" 不是一个关键字,你应该使用 "func"。
  2. 你调用了 Changedlist 函数时使用了 changedlist
  3. 在 for 循环中,变量 r 是数组项的一个副本,所以如果你修改它,数组不会受到影响。我在这里使用 (*addressList)[k] = r 来修改数组。另外,你也可以通过索引直接修改,比如 (*addressList)[k].Name = xxx,而不需要使用 r

希望这可以帮到你。

英文:
package main

import (
	"errors"
	"fmt"
)

type Mail struct {
	Name    string
	Address string
	Status  bool
	Error   error
}

func List() {
	var addressList = make([]Mail, 2)
	addressList[0].Name = "Name"
	addressList[0].Address = "Address"
	addressList[1].Address = "Address"
	addressList[1].Name = "Name1"
	fmt.Println(addressList)
	newAddress := Changedlist(&addressList)
	fmt.Println(newAddress)
}
func Changedlist(addressList *[]Mail) *[]Mail {
	for k, r := range *addressList {
		if r.Name == "Name1" {
			r.Status = false
			r.Error = errors.New("Error in the name")
			(*addressList)[k] = r
			continue
		}
		r.Status = true
		r.Error = nil
		(*addressList)[k] = r
	}
	return addressList
}

func main() {
	List()
}

// output
[{Name Address false <nil>} {Name1 Address false <nil>}]
&[{Name Address true <nil>} {Name1 Address false Error in the name}]

This is my code, it's not perfect but works correctly.
There are some things you got wrong.

  1. "function" is not a keyword, you should use "func" instead.
  2. You call the function Changedlist with changedlist.
  3. in for loop, the variable r is a copy of the array item, so if you changed it, the array is not affected, I used (*addressList)[k] = r here to change the array. Also, you could modify it with index like (*addressList)[k].Name = xxx without using r

That's all
Hope this can help you ...

https://play.golang.org/p/zAJ5aJpwwA

huangapple
  • 本文由 发表于 2016年11月17日 15:15:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/40648828.html
匿名

发表评论

匿名网友

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

确定