我做了以下事情:
availableObjs[]interface{}GoPlayground 代码: https://play.golang.org/p/jdHpueokrEk
尝试在线搜索。
内联相同代码:
package main
import (
"fmt"
"reflect"
)
////// Parent Interface which has Display() fn.
type Parent interface {
Display()
}
// 2 Child structs implementing their Display() fn.
type Child1 struct {
name1 string
}
type Child2 struct {
name2 string
}
func (c1 Child1) Display() {
fmt.Println("c1Name : ", c1.name1)
}
func (c2 Child2) Display() {
fmt.Println("c2Name : ", c2.name2)
}
////////////////////////////////////////////
// Maintains the created objects
var availableObjs []interface{}
func main() {
//// Creating 2 objects
c1 := Child1{"Child1"}
c2 := Child2{"Child2"}
// Adding 2 objects to availableObjs
availableObjs = append(availableObjs, c1)
availableObjs = append(availableObjs, c2)
// Now, want to fetch the Object from Interface and call its respective Display() fn.
for _, obj := range availableObjs {
fmt.Println("")
fmt.Println("Obj Got = ",obj)
fmt.Println("Obj type = ",reflect.TypeOf(obj))
//obj.Display() // <-- Problem Line
}
}
需要做的事情:需要输入关于从数组接口(interface)获取对象后如何调用 Display() 函数的信息。
最佳答案
有两种方法可以做到这一点:一种是不使用空接口(interface),而是使用正确的父接口(interface)来声明 slice :
// Maintains the created objects
var availableObjs []Parent
请注意,Parent 接口(interface)的命名表明您正在使用继承概念来处理接口(interface),这不是我们在 Go 中使用的东西。您必须将界面更像是一种行为。在这种特殊情况下,您想要表示能够“显示”的事物的行为,因此您可以调用接口(interface) Displayer。
这种命名约定,将 -er 附加到接口(interface)名称,是 Go 中非常常见的模式,即使有时您会得到一些奇怪的名称:)
从同样的意义上讲,Child 结构实际上并不是 Parent 接口(interface)的子级,它们只是隐式满足该接口(interface)的结构。
它们可以同时满足任意数量的接口(interface)。例如,如果他们有一个 String() 方法,他们也会满足 fmt.Stringer 接口(interface)。
现在,第二个选项是使用类型断言,使用 switch 语句或类型语句:
switch t := obj.(type) {
case Parent:
t.Display() // note that 't' is the new typed variable
}
或者
t, ok := obj.(Parent)
if ok {
t.Display()
}
请注意,上面的 ok 变量可以省略,但在这种情况下,如果类型断言不匹配,代码将崩溃。
关于function - 添加到 []interface{} 的对象。现在需要获取对象并调用对象各自的 Display() fn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56570184/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信
我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser