1
0
Fork 0
This commit is contained in:
Alex Kotov 2020-11-17 07:48:34 +05:00
commit e16855e607
Signed by: kotovalexarian
GPG Key ID: 553C0EBBEB5D5F08
2 changed files with 57 additions and 0 deletions

View File

@ -0,0 +1,2 @@
all:
go run main.go

55
1-pointers-in-go/main.go Normal file
View File

@ -0,0 +1,55 @@
package main
import (
"fmt"
"time"
)
type Person struct {
firstName string
lastName string
birthday time.Time
}
func main() {
birthday, _ := time.Parse("2006-Jan-02", "1994-Aug-10")
person := Person{
firstName: "Alex",
lastName: "Kotov",
birthday: birthday,
}
printPersonByValue(person)
printPersonByRefSafe(&person)
printPersonByRefUnsafe(&person)
printPersonByRefSafe(nil)
printPersonByRefUnsafe(nil)
}
func printPersonByValue(person Person) {
fmt.Println("=== by value =====================================")
fmt.Println("First name:", person.firstName)
fmt.Println("Last name: ", person.lastName)
fmt.Println("Birthday: ", person.birthday)
}
func printPersonByRefSafe(person *Person) {
fmt.Println("=== by reference (safe) ==========================")
if person == nil {
fmt.Println("nil pointer, skip...")
return
}
fmt.Println("First name:", person.firstName)
fmt.Println("Last name: ", person.lastName)
fmt.Println("Birthday: ", person.birthday)
}
func printPersonByRefUnsafe(person *Person) {
fmt.Println("=== by reference (unsafe) ========================")
fmt.Println("First name:", person.firstName)
fmt.Println("Last name: ", person.lastName)
fmt.Println("Birthday: ", person.birthday)
}