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

如何解决? 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")

}


Smart猫小萌
浏览 212回答 2
2回答

慕娘9325324

Cache是一种类型。要在Cache对象上调用方法,您必须这样做。func (c *Cache) Set(k string, v string) {&nbsp; &nbsp; for mi, _ := range c.Segment[0].Key {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;fmt.Println(c.Segment[0].Val[mi])&nbsp;&nbsp;&nbsp; &nbsp; }}注意它的c.Segment[0].Keyandc.Segment[0].Val[mi]而不是Cache.Segment[0].KeyandCache.Segment[0].Val[mi]Go Playground不相关的建议:在您的代码上运行gofmt。它指出违反了经常遵循的 go 代码风格指南。我注意到你的代码中的一些。

森林海

您需要为 *Cache 提供一个变量才能使用它,例如:package mainimport "fmt"type Slot struct {&nbsp;&nbsp;&nbsp; &nbsp; Key []string&nbsp; &nbsp; Val []string}type Cache struct{&nbsp; &nbsp; Segment [3615]Slot}func NewCache(s int) *Cache{&nbsp; &nbsp; num:=3615&nbsp; &nbsp; Cacheobj:=new(Cache)&nbsp; &nbsp; for i := 0; i < num; i++ {&nbsp; &nbsp; &nbsp; &nbsp; Cacheobj.Segment[i].Key = make([]string, s)&nbsp; &nbsp; &nbsp; &nbsp; Cacheobj.Segment[i].Val = make([]string, s)&nbsp; &nbsp; }&nbsp; &nbsp; return Cacheobj}func (c *Cache)Set(k string, v string) {&nbsp; &nbsp; &nbsp; &nbsp; for mi, _:= range c.Segment[0].Key { // Had to change mk to _ because go will not compile when variables are declared and unused&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;fmt.Println(c.Segment[0].Val[mi])&nbsp;&nbsp;&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; Cache1:=NewCache(100)&nbsp; &nbsp; Cache1.Set("a01", "111111")}http://play.golang.org/p/1vLwVZrX20
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go