Using struct
and a function that is supposed to print out the struct's elements, I have written this simple program:
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)
}
When I run it I get the error go:16: type Salutation is not an expression
. What goes wrong here?
Interestingly enough, when I change the definition of s
to var s = Salutation {"Alex", "Hi"}
it works just fine. But they are basically different syntactic ways to define the same entity. That's why I don't understand the source of the error.
The error is on this line
var s = Salutation
The thing to the right of the = must evaluate to a value. Salutation
is a type, not value. Here are three ways to declare s:
var s Salutation // variable declaration using a type
var s = Salutation{} // variable declaration using a value
s := Salutation{} // short variable declaration
The result of all three declarations is identical. The third variation is usually preferred to the second, but cannot be used to declare a package-level variable.
See the language specification for all of the details on variable declarations.
The variable declaration and field initializations can be combined into a single statement:
var s = Salutation{name: "Alex", greeting: "Hello"} // variable declaration
s := Salutation{name: "Alex", greeting: "Hello"} // short variable declaration
4th way:
var s *Salutation = &( Salutation{} );
I always pass structs by reference, not value. And always pass primitives by value.
Your method re-written as a reciever method:
func (s *Salutation) Greet()() {
fmt.Println(s.name)
fmt.Println(s.greeting)
}
Full Example:
package main
import "fmt"
func NewSalutation()(*Salutation){
return &( Salutation{} );
}
type Salutation struct {
name string
greeting string
}
func (s *Salutation) Greet()() {
fmt.Println(s.name)
fmt.Println(s.greeting)
}
func main() {
var s *Salutation; //:<--Null
s = NewSalutation() //:<--Points To Instance
s.name = "Alex"
s.greeting = "Hi"
s.Greet();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With