YouTip LogoYouTip

Go Functions and Error Handling

Functions

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, fmt.Errorf("division by zero")
    }
    return a / b, nil
}

result, err := divide(10, 3)
if err != nil {
    log.Fatal(err)
}

Structs

type Rectangle struct {
    Width, Height float64
}

func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

Summary

  • Go uses explicit error handling (no exceptions)
  • Methods are defined on structs with receivers
← Go Goroutines and ChannelsGo Tutorial - Hello World β†’