go-golang编译错误: type has no method

标签 go

如何解决? https://play.golang.org/p/aOrqmDM91J

:28: Cache.Segment undefined (type Cache has no method Segment)

:29: Cache.Segment undefined (type Cache has no method 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")
}

最佳答案

Cache 是一种类型。要在 Cache 对象上调用方法,您必须这样做。

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 代码风格指南。我注意到您的代码中有一些内容。

关于go-golang编译错误: type has no method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35665362/

相关文章:

go - 来自 r.URL.Query() 的键映射不一致

go - 在 Go 中重复函数调用的 For 循环

go - 这是 Go 中组合的有效实现吗?

go - 在Golang中封装 `sort`接口(interface)

go - 如何在Go中向现有类型添加新方法?

mongodb - Go 官方 mongo-driver 中如何实现结构体字段验证?

转到 : Deadlock issue with go channel and select

go - 未找到类型 InteractionCallback,atom 正在删除导入语句

go - 如何从 Go 中的另一个文件调用函数

go - gin-gonic 是否并行处理请求?