如何使用接口中的方法修改结构体中的字段?

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

How to modify fields in struct using methods from interface?

问题

我正在写一个小项目来学习一些Google Go的知识,但是在编码几个小时后,我发现有一个问题我自己无法解决,也在互联网上找不到答案。我的项目将包含几个在实现一个接口的变量上操作的算法。所有类型的共同之处是我可以通过评分来对它们进行评估和比较,所以接口中定义的一个方法应该是SetRating(x int)。问题是,由于Go是值传递的,我无法修改其中的任何字段。这里有一个例子:

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

我试图找出人们在这种情况下使用的解决方法:
http://play.golang.org/p/PUuOBZ4uM-

但我认为这个解决方案很丑陋,因为我需要在调用函数中知道接口的所有实现(进行类型转换),而且我真的想避免这样做,希望编写一些通用的代码,可以处理任何实现了我的接口的类型,只需要知道每个实现都有setRating(x int)和getRating(x int)方法。

有什么提示吗?
(对于我的英语和问题描述不好,还在学习中。)

英文:

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

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

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.)

答案1

得分: 7

你需要使用指针,否则你无法修改底层结构。以下是代码的翻译:

package main

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

type S1 struct {
	X int
}

func (this *S1) Set(x int) {
	this.X = x
	println("设置值")
}

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



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

}

请注意,这只是代码的翻译,不包括任何其他内容。

英文:

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()

}

huangapple
  • 本文由 发表于 2014年6月6日 03:36:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/24068779.html
匿名

发表评论

匿名网友

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

确定