2013-04-11 14 views
5

voglio definire un tipo come questo:operazione non valida: s [k] (indice di tipo * S)

type S map[string]interface{} 

e voglio aggiungere un metodo al tipo in questo modo:

func (s *S) Get(k string) (interface {}){ 
    return s[k] 
} 

quando il programma viene eseguito, c'era un errore come questo:

invalid operation: s[k] (index of type *S) 

Allora, come faccio a definire il tipo e aggiungere il metodo per il tipo?

risposta

10

Per esempio,

package main 

import "fmt" 

type S map[string]interface{} 

func (s *S) Get(k string) interface{} { 
    return (*s)[k] 
} 

func main() { 
    s := S{"t": int(42)} 
    fmt.Println(s) 
    t := s.Get("t") 
    fmt.Println(t) 
} 

uscita:

map[t:42] 
42 

mappe sono tipi di riferimento, che contengono un puntatore alla mappa sottostante, in modo che normalmente non avrebbe bisogno di usare un puntatore per s . Ho aggiunto un metodo per enfatizzare il punto. Ad esempio,

package main 

import "fmt" 

type S map[string]interface{} 

func (s S) Get(k string) interface{} { 
    return s[k] 
} 

func (s S) Put(k string, v interface{}) { 
    s[k] = v 
} 

func main() { 
    s := S{"t": int(42)} 
    fmt.Println(s) 
    t := s.Get("t") 
    fmt.Println(t) 
    s.Put("K", "V") 
    fmt.Println(s) 
} 

uscita:

map[t:42] 
42 
map[t:42 K:V] 
+3

forse espongono un po 'sul puntatore vs ricevitori di valore, e il motivo per cui mappa può lavorare con un ricevitore valore? – cthom06

Problemi correlati