dragon321723 2016-12-21 20:08
浏览 24

返回文字与指针

Trying to make a slice and having problems with literals and pointers. It looks like when appending onto my slice it does not like the fact of being handed a pointer. For instance I have a package type I made called components and holds type Component. See below.

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
}

Now I am attempting to make a slice to put all my components into I am making spellcasting components like Snow,Sand,Sunbeam,Springwater etc.

    //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")

ERROR HAPPENS HERE ON COMPLILE: compSlice := make([]components.Component, 5) compSlice = append(compSlice, SpringWater, Sand)

ERROR: Cannot use Sand as type (*components.Component) as type components.Component in append.

Now using the Setters and Setting the Fields DIRECT I can add it to a slice however using the method it returns a *pointer and the Slice will not comply. I am just not understanding and having a difficult issue. Keep in mind I am new to programming and basically come from scripting so forgive me on this and have seen similar questions but do not understand in this context.

  • 写回答

3条回答 默认 最新

  • duanhuang2150 2016-12-21 20:19
    关注

    Go hides the difference between values and pointers in several places, but not everywhere.

    In this situation you will have to dereference Sand and write compSlice = append(compSlice, SpringWater, *Sand)

    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题