为了账号安全,请及时绑定邮箱和手机立即绑定

go - golang 编译错误:类型没有方法

go - golang 编译错误:类型没有方法

Go
Smart猫小萌 2021-12-20 10:09:26
如何解决? https://play.golang.org/p/aOrqmDM91J:28: Cache.Segment 未定义(类型 Cache 没有方法 Segment):29: Cache.Segment 未定义(类型 Cache 没有方法 Segment)package mainimport "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 回答

?
慕娘9325324

TA贡献1783条经验 获得超5个赞

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].Keyandc.Segment[0].Val[mi]而不是Cache.Segment[0].KeyandCache.Segment[0].Val[mi]


Go Playground


不相关的建议:在您的代码上运行gofmt。它指出违反了经常遵循的 go 代码风格指南。我注意到你的代码中的一些。


查看完整回答
反对 回复 2021-12-20
?
森林海

TA贡献2011条经验 获得超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


查看完整回答
反对 回复 2021-12-20
  • 2 回答
  • 0 关注
  • 198 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号