2016-02-27 90 views
0

如何解決? https://play.golang.org/p/aOrqmDM91Jgo - golang編譯錯誤:類型沒有方法

: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") 
} 
+1

由於鏈接可以去隨着時間的推移陳舊/變化,所以最好直接包含你的代碼到您的帖子。 – Castaglia

+0

感謝您的建議 – noname

回答

1

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您的代碼。它指向違反定期遵循的代碼風格指南。我注意到你的代碼中有一些。

0

你需要給一個變量*高速緩存來使用它,像:

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

相關問題