noname
noname

Reputation: 31

go - golang compile error: type has no method

how to solve it? 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")
}

Upvotes: 3

Views: 11548

Answers (2)

Aruna Herath
Aruna Herath

Reputation: 6531

Cache is a type. To call a method on a Cache object you have to do this.

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

Note its c.Segment[0].Key and c.Segment[0].Val[mi] instead of Cache.Segment[0].Key and Cache.Segment[0].Val[mi]

Go Playground

unrelated suggestion: Run gofmt on your code. It points to violations of regularly followed style guidelines for go code. I notice a few on your code.

Upvotes: 3

Datsik
Datsik

Reputation: 14824

You need to give a variable to *Cache to use it, something like:

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

Upvotes: -2

Related Questions