Advertisement
cydside

Simple Go object with functional programming

May 14th, 2023 (edited)
1,366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.50 KB | None | 0 0
  1. package person
  2.  
  3. type Name string
  4.  
  5. type Age int
  6.  
  7. type Person struct {
  8.     name Name
  9.     age  Age
  10. }
  11.  
  12. func NewPerson(name Name, age Age) *Person {
  13.     return &Person{
  14.         name: name,
  15.         age:  age,
  16.     }
  17. }
  18.  
  19. func GetName(p *Person) Name {
  20.     return p.name
  21. }
  22.  
  23. func SetName(p *Person, name Name) *Person {
  24.     return &Person{
  25.         name: name,
  26.         age:  p.age,
  27.     }
  28. }
  29.  
  30. func GetAge(p *Person) Age {
  31.     return p.age
  32. }
  33.  
  34. func SetAge(p *Person, age Age) (*Person, error) {
  35.     if age < 0 {
  36.         return nil, fmt.Errorf("age cannot be negative: %d", age)
  37.     }
  38.     return &Person{
  39.         name: p.name,
  40.         age:  age,
  41.     }, nil
  42. }
  43.  
  44.  
  45. //___________________________________________________________________________________________________
  46.  
  47. package main
  48.  
  49. import (
  50.     "fmt"
  51.     "person"
  52. )
  53.  
  54. func main() {
  55.     p := person.NewPerson("Alice", 30)
  56.  
  57.     // Get the person's name using the GetName function
  58.     name := person.GetName(p)
  59.     fmt.Printf("Name: %s\n", name)
  60.  
  61.     // Set the person's name using the SetName function
  62.     p = person.SetName(p, "Bob")
  63.     name = person.GetName(p)
  64.     fmt.Printf("Name: %s\n", name)
  65.  
  66.     // Get the person's age using the GetAge function
  67.     age := person.GetAge(p)
  68.     fmt.Printf("Age: %d\n", age)
  69.  
  70.     // Set the person's age using the SetAge function
  71.     var err error
  72.     p, err = person.SetAge(p, 40)
  73.     if err != nil {
  74.         panic(err)
  75.     }
  76.     age = person.GetAge(p)
  77.     fmt.Printf("Age: %d\n", age)
  78. }
  79.  
  80.  
  81.  
  82.  
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement