Go - Golang编译错误:类型没有方法。

3
如何解决这个问题? https://play.golang.org/p/aOrqmDM91J

:28:Cache.Segment未定义(Cache类型没有Segment方法)

:29:Cache.Segment未定义(Cache类型没有Segment方法)

package main
import "fmt"

type Slot struct {  
    Key []string
    Val []string
}

type Cache struct{
    Segment [3615]Slot
}

func NewCache(s int) *Cache{
    num:=3615
    Cacheobj:=new(Cache)
    
    for i := 0; i < num; i++ {
        Cacheobj.Segment[i].Key = make([]string, s)
        Cacheobj.Segment[i].Val = make([]string, s)
    }
            
    return Cacheobj
}

func (*Cache)Set(k string, v string) {
        for mi, mk := range Cache.Segment[0].Key {
         fmt.Println(Cache.Segment[0].Val[mi])  
    }
}
func main() {
    Cache1:=NewCache(100)
    Cache1.Set("a01", "111111")
}

2
由于链接可能会随着时间的推移而失效/更改,最好将您的代码直接包含在您的帖子中。 - Castaglia
感谢您的建议。 - noname
2个回答

3

缓存是一种类型。要在缓存对象上调用方法,您需要执行以下步骤。

func (c *Cache) Set(k string, v string) {
    for mi, _ := range c.Segment[0].Key {
         fmt.Println(c.Segment[0].Val[mi])  
    }
}

请注意使用c.Segment[0].Keyc.Segment[0].Val [mi]而不是Cache.Segment[0].KeyCache.Segment[0].Val[mi]Go Playground 无关的建议:在您的代码上运行gofmt,它指出了遵循go代码常规样式指南的违规情况。我注意到你的代码中有一些。

-2

你需要给*Cache一个变量才能使用它,例如:

package main
import "fmt"

type Slot struct {  
    Key []string
    Val []string
}

type Cache struct{
    Segment [3615]Slot
}

func NewCache(s int) *Cache{
    num:=3615
    Cacheobj:=new(Cache)

    for i := 0; i < num; i++ {
        Cacheobj.Segment[i].Key = make([]string, s)
        Cacheobj.Segment[i].Val = make([]string, s)
    }

    return Cacheobj
}

func (c *Cache)Set(k string, v string) {
        for mi, _:= range c.Segment[0].Key { // Had to change mk to _ because go will not compile when variables are declared and unused
         fmt.Println(c.Segment[0].Val[mi])  
    }
}
func main() {
    Cache1:=NewCache(100)
    Cache1.Set("a01", "111111")
}

http://play.golang.org/p/1vLwVZrX20


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接