doubailian4459 2019-01-10 03:56
浏览 29
已采纳

如何编写将数组成员分配给self的方法

I have an array of structs and a method for finding a struct with a given ID within that array. If it exists, I want to copy it into the struct itself. But I can't make it work.

I can make it work with Marshal and Unmarshal, but I don't think this is a good solution.

https://play.golang.org/p/16giIQ0R1Hv

package main

import (
    "fmt"
)

type Tmp struct {
    ID  int
    Val int
}

var members []Tmp

func (o *Tmp) FindID(id int) {
    for i := range members {
        if members[i].ID == id {
            fmt.Println("found!")
            fmt.Println(members[i])
            tmp := members[i]
            o = &tmp
        }
    }
}

func main() {
    for i := 0; i < 5; i++ {
        o := Tmp{ID: i, Val: i * 2}
        members = append(members, o)
    }
    fmt.Println(members)
    a := Tmp{}
    a.FindID(3)
    fmt.Println(a)
}

This outputs:

[{0 0} {1 2} {2 4} {3 6} {4 8}]
found!
{3 6}
{0 0}
  • 写回答

1条回答 默认 最新

  • drfif48428 2019-01-10 04:47
    关注

    You can use the dereference operator to assign a value to a pointer

    *o = members[i]
    

    So, in your case:

    func (o *Tmp) FindID(id int) bool {
        for i := range members {
            if members[i].ID == id {
                *o := members[i]
                return true
            }
        }
        return false
    }
    

    I took the liberty to make the function indicate (via return values) whether it actually found anything or not; of course, you can ignore that change.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址