如何使用接口中的方法修改结构中的字段? [英] How to modify fields in struct using methods from interface?

查看:150
本文介绍了如何使用接口中的方法修改结构中的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个小程序来学习一些Google Go,但经过几个小时的编码后,我发现有一个问题是我自己无法解决的,这两个问题都没有在互联网上找到。我的项目将包含几个运算变量实现一个接口的算法。所有类型的共同之处在于我可以对它们进行评分并通过此评分进行比较,因此Interface中定义的一个方法应该是SetRating(x int),问题是,因为Go正在复制值 - 我无法修改任何字段在里面。以下是示例

I'm writing a small project to learn some Google Go, but after few hours of coding I found that there's an issue I can't solve on my own, neither found on the internet. My project will be containing few algorithms operating on variables implementing one interface. The thing in common of all types is that I can rate them and compare by this rating so one of methods defined in Interface should be SetRating(x int) and the problem is, since Go is copying value - I can't modify any field in it. Here's example

http://play.golang。 org / p / 4nyxulwzNo

试图找出人们在这个约定中使用变通方法:
http://play.golang.org/p/PUuOBZ4uM-

Trying to find out that people is using workarounds in this convention: http://play.golang.org/p/PUuOBZ4uM-

但我认为这个解决方案是一个丑陋的,因为我需要知道我的接口的所有实现在调用func(转换类型),并且真的想要避免这种情况,并编写一些通用代码,可以实现我的接口的任何类型,只是知道每个实现都有方法setRating(x int)和getRating(x int)。

but I think this solution is a ugly, because I need to know all implementations of my interface in invoke func (to cast types) and really want to avoid this and write some universal code that can get any types implementing my Interface, just knowing that every implementation have method setRating(x int) and getRating(x int).

任何提示?
(对不起,英文不好,问题描述仍在学习中)。

Any hints? (Sorry for poor English and problem's description, still learning.)

推荐答案

您需要使用指针,否则您并未修改底层结构: http://play.golang.org/p/l3X4gTSAnF

You need to use the pointer because otherwise you are not modifying the underlying structure: http://play.golang.org/p/l3X4gTSAnF

package main

type Setter interface {
    Set(x int)
    Print()
}

type S1 struct {
    X int
}

func (this *S1) Set(x int) {
    this.X = x
    println("Setting value")
}

func (this *S1) Print(){
    println(this.X)
}



func main() {
    var s1 Setter 
    s1 = &S1{}
    s1.Set(5)
    s1.Print()

}

这篇关于如何使用接口中的方法修改结构中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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