3

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")
}
2
  • 2
    Since links can go stale/change over time, it's best to include your code directly into your post. Commented Feb 27, 2016 at 3:39
  • thanks for your suggestion Commented Feb 27, 2016 at 4:10

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

-2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.