doushang2021 2014-11-13 12:57
浏览 24
已采纳

惯用的golang:访问和更新结构中的项目

So I am trying to write some code that allows me to edit values in an array in a struct. This example uses "Status" as a possible value to alter, but this is just a simplification to try to get my intent across.

package main

import(
  "fmt"
)

type Parent struct {
  Children []Child
}

type Child struct {
  Status string
}

func (p *Parent) Add() *Child {
  var child Child
  child.Status = "1"
  p.Children = append(p.Children, child)
  return &p.Children[len(p.Children)-1]
}

func main() {
  var p Parent
  child := p.Add()
  child.Status = "2"
  fmt.Println(p)
  fmt.Println(child)
}

This doesn't feel "proper". How should I do this in golang? Certainly I could pass the value in as a parameter, but in my particular case I would like to edit function pointers that are inside the Child struct (not in this code to keep it short) after having added the child. That feels nicer, but maybe I just need to pass them as parameters to the Add method?

eg

func (p *Parent) Add(fn1 func(), fn2 func()) *Child {

Anyway just wondering if anybody has any thoughts on this type of situation.

  • 写回答

3条回答 默认 最新

  • duanboshe0001 2014-11-13 13:18
    关注

    I think you should create the Child outside of the Add method and pass it in. If you want to manipulate the Child, do that before you passed it in. You might use methods on the Child struct to do that:

    func (c *Child) Init(fn1 func(), fn2 func()) {
      c.Status = "1"
      ...
    }
    
    func (p *Parent) Add(c *Child) *Child {
      p.Children = append(p.Children, c)
      return c
    }
    
    func main() {
      var p Parent
      var child Child
      child.Init(...)       // <- pass something in there...
      p.Add(&child)
      child.Status = "2"
      fmt.Println(p)
      fmt.Println(child)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据