试图对文字与指针进行切分并产生问题。它看起来像追加到我的切片时,它不喜欢被递交指针的事实。例如,我有一个我称为组件的包类型,并保存类型组件。见下文。文字与指针的对比
package components
import()
type Component struct {
Name string
Element string
Color string
}
func (c *Component) SetName(name string) {
c.Name = name
}
func (c *Component) SetElement(element string) {
c.Element = element
}
func (c *Component) SetColor(color string) {
c.Color = color
}
func (c *Component) GetName() string {
return c.Name
}
func (c *Component) GetColor() string {
return c.Color
}
func (c *Component) GetElement() string {
return c.Element
}
func NewComponent(name string, color string, element string) *Component {
c := &Component{}
c.SetName(name)
c.SetColor(color)
c.SetElement(element)
return c
}
现在我试图做一个切片把我所有的组件集成到我正在施法部件,例如雪地,沙地,新光,泉水等
//Creating SpringWater Component with Setters
SpringWater := components.Component{}
SpringWater.SetName("SpringWater")
SpringWater.SetColor("Blue")
SpringWater.SetElement("Water")
//Creating Sand Component using the Constructor
Sand := components.NewComponent("Sand", "Red", "Earth")
错误发生在这里请编译: compSlice:=使([] components.Component,5) compSlice =追加(compSlice,泉水,砂)
ERROR:无法使用萨nd作为类型(* components.Component)作为类型components.Component附加。
现在使用Setters和设置字段直接我可以将它添加到切片,但使用它返回一个*指针的方法和切片将不符合。我只是不理解,并有一个困难的问题。请记住,我是编程新手,基本上来自脚本编写,所以请原谅我,并且看到过类似的问题,但在这种情况下不理解。
并在您的设计评论。如果你想隐藏你的结构成员,比如'SetName',那么你应该让它们变成小写。如果您将它们放在UpperCase上,那么它们将直接公开给所有人使用。我会这样做,因为我认为功能隐藏是愚蠢的,虽然你需要Go界面,但无论如何。 –
好的,我会更多地讨论它,让你们知道我想出了什么,或者如果我还在挣扎。我不知道有帮助的人会很快回复我哇!多谢你们 – RedBloodMage