我想知道当一个指向另一个时,是否有在嵌入式函数中应用“多态性”的解决方案。例如我有以下界面:
type Client interface {
Get(string) string
GetResource() string
}
和默认实现:
type ClientImpl struct {
}
func (c ClientImpl) Get(s string) string {
return fmt.Sprintf("Impl [%s]", s)
}
func (c ClientImpl) GetResource() string {
return c.Get("resource") # points to Get
}
在其他实现中(例如测试)我想用其他响应替换默认的 Get 函数,但保持 GetResource 方法不变
type TestImpl struct {
ClientImpl
}
func (t TestImpl) Get(s string) string {
return fmt.Sprintf("Test [%s]", s)
}
Override 函数在直接调用时有效,但在从嵌入式函数调用时无效。查看以下测试用例产生的输出:
c := ClientImpl{}
t := TestImpl{}
fmt.Println("WORKS:")
fmt.Println("Client Get:", c.Get("aaa"))
fmt.Println("Test Get:", t.Get("aaa"))
fmt.Println("DOSN'T WORK :(")
fmt.Println("Client GetRes:", c.GetResource())
fmt.Println("Test GetRes:", t.GetResource())
# WORKS:
# Client Get: Impl [aaa]
# Test Get: Test [aaa]
# DOSN'T WORK :(
# Client GetRes: Impl [resource]
# Test GetRes: Impl [resource]
如何让 last print 输出字符串 Test [resource]?
Go Playground 示例:https://play.golang.org/p/b-vM1_W3oB
最佳答案
在您的示例中,您需要在其自己的界面中隔离 Get 函数。
这里有两种类似的方法:
// one way to do this :
type Getter interface {
Get(string) string
}
type ClientImpl struct {
}
func (c ClientImpl) Get(s string) string {
return fmt.Sprintf("Impl [%s]", s)
}
type TestImpl struct {
}
func (t TestImpl) Get(s string) string {
return fmt.Sprintf("Test [%s]", s)
}
// write a bare GetResource function :
func GetResource(c Getter) string {
return c.Get("resource")
}
https://play.golang.org/p/R2XciBx_yk
// another way : store the "Getter" as a field in a struct
type Getter interface {
Get(string) string
}
type ProdGetter struct {
}
func (c ProdGetter) Get(s string) string {
return fmt.Sprintf("Impl [%s]", s)
}
type TestGetter struct {
}
func (t TestGetter) Get(s string) string {
return fmt.Sprintf("Test [%s]", s)
}
// create a struct, which holds a Getter, and has methods to do stuff with it :
type Client struct {
Getter
}
func (c *Client) GetResource() string {
return c.Get("resource")
}
关于Golang 覆盖嵌入式函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43250443/
我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah
我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re
我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)
我正在尝试用ruby中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了
我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin
在Ruby类中,我重写了三个方法,并且在每个方法中,我基本上做同样的事情:classExampleClassdefconfirmation_required?is_allowed&&superenddefpostpone_email_change?is_allowed&&superenddefreconfirmation_required?is_allowed&&superendend有更简洁的语法吗?如何缩短代码? 最佳答案 如何使用别名?classExampleClassdefconfirmation_required?is_a
我们的git存储库中目前有一个Gemfile。但是,有一个gem我只在我的环境中本地使用(我的团队不使用它)。为了使用它,我必须将它添加到我们的Gemfile中,但每次我checkout到我们的master/dev主分支时,由于与跟踪的gemfile冲突,我必须删除它。我想要的是类似Gemfile.local的东西,它将继承从Gemfile导入的gems,但也允许在那里导入新的gems以供使用只有我的机器。此文件将在.gitignore中被忽略。这可能吗? 最佳答案 设置BUNDLE_GEMFILE环境变量:BUNDLE_GEMFI
如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只
说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时
我需要一个通过输入字符串进行计算的方法,像这样function="(a/b)*100"a=25b=50function.something>>50有什么方法吗? 最佳答案 您可以使用instance_eval:function="(a/b)*100"a=25.0b=50instance_evalfunction#=>50.0请注意,使用eval本质上是不安全的,尤其是当您使用外部输入时,因为它可能包含注入(inject)的恶意代码。另请注意,a设置为25.0而不是25,因为如果它是整数a/b将导致0(整数)。