Created
August 14, 2021 09:07
-
-
Save petrjahoda/20d6c37e7fa54843d21569dd81d2dbdc to your computer and use it in GitHub Desktop.
6. Changing the name with a method, passing a pointer and interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type Car struct { | |
name string | |
} | |
type Truck struct { | |
name string | |
} | |
type Vehicle interface { | |
changeNameUsingMethodWithPointer() | |
} | |
func main() { | |
bmw := Car{name: "bmw is the best car"} | |
volvo := Truck{name: "volvo is the best truck"} | |
bmw.name = changeNameOfCar(bmw) | |
volvo.name = changeNameOfTruck(volvo) | |
changeNameOfCarUsingPointer(&bmw) | |
changeNameOfTruckUsingPointer(&volvo) | |
volvo.name = volvo.changeNameUsingMethod() | |
bmw.name = bmw.changeNameUsingMethod() | |
bmw.changeNameUsingMethodWithPointer() | |
volvo.changeNameUsingMethodWithPointer() | |
var vehicles []Vehicle | |
vehicles = append(vehicles, &bmw) | |
vehicles = append(vehicles, &volvo) | |
for _, vehicle := range vehicles { | |
vehicle.changeNameUsingMethodWithPointer() | |
} | |
fmt.Println(bmw.name) | |
fmt.Println(volvo.name) | |
} | |
func changeNameOfCar(c Car) string { | |
return c.name + "\n\t... changed with simple function" | |
} | |
func changeNameOfTruck(t Truck) string { | |
return t.name + "\n\t... changed with simple function" | |
} | |
func changeNameOfCarUsingPointer(c *Car) { | |
c.name = c.name + "\n\t... changed using pointer" | |
} | |
func changeNameOfTruckUsingPointer(t *Truck) { | |
t.name = t.name + "\n\t... changed using pointer" | |
} | |
func (c Car) changeNameUsingMethod() string { | |
return c.name + "\n\t... changed with method" | |
} | |
func (t Truck) changeNameUsingMethod() string { | |
return t.name + "\n\t... changed with method" | |
} | |
func (c *Car) changeNameUsingMethodWithPointer() { | |
c.name = c.name + "\n\t... changed with method using pointer" | |
} | |
func (t *Truck) changeNameUsingMethodWithPointer() { | |
t.name = t.name + "\n\t... changed with method using pointer" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment