commit e16855e607129f4121d7b04ae7a7fac137011804 Author: Alex Kotov Date: Tue Nov 17 07:48:34 2020 +0500 Add code diff --git a/1-pointers-in-go/Makefile b/1-pointers-in-go/Makefile new file mode 100644 index 0000000..d476aff --- /dev/null +++ b/1-pointers-in-go/Makefile @@ -0,0 +1,2 @@ +all: + go run main.go diff --git a/1-pointers-in-go/main.go b/1-pointers-in-go/main.go new file mode 100644 index 0000000..bd8bf9e --- /dev/null +++ b/1-pointers-in-go/main.go @@ -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) +}