2014-12-13 16 views
18

Utilizzando struct e una funzione che dovrebbe stampare gli elementi della struct, ho scritto questo semplice programma:errore: struct tipo non è espressione

package main 

import "fmt" 

type Salutation struct { 
    name  string 
    greeting string 
} 

func Greet(salutation Salutation) { 
    fmt.Println(salutation.name) 
    fmt.Println(salutation.greeting) 
} 

func main() { 
    var s = Salutation 
    s.name = "Alex" 
    s.greeting = "Hi" 
    Greet(s) 
} 

quando l'eseguo ottengo l'errore go:16: type Salutation is not an expression. Cosa va storto qui?

È interessante notare che quando cambio la definizione di s a var s = Salutation {"Alex", "Hi"} funziona perfettamente. Ma sono fondamentalmente diversi modi sintattici per definire la stessa entità. Ecco perché non capisco la fonte dell'errore.

risposta

31

L'errore è su questa linea

var s = Salutation 

La cosa da destra dei = deve essere valutata come un valore. Salutation è di tipo, non di valore. Ecco tre modi per dichiarare:

var s Salutation  // variable declaration using a type 

var s = Salutation{} // variable declaration using a value 

s := Salutation{}  // short variable declaration 

Il risultato di tutte e tre le dichiarazioni è identico. La terza variante di solito è preferibile alla seconda, ma non può essere utilizzata per dichiarare una variabile a livello di pacchetto.

Vedere le specifiche della lingua for all of the details on variable declarations.

+0

'type salution struct {}' è possibile accedere a 'struct'' fmt.Println (salution, "struct typee") '@Cerise Limon – muthukumar

Problemi correlati