Go · lesson 15 of 30 · Data, functions and the command lineGive a struct methods
A method belongs to a type. With *Volume it can change the volume itself; with Volume it gets a copy.
15-methods.go Download 15-methods.go
package main
import "fmt"
type Volume struct {
Name string
Size, Used float64
}
func (v Volume) Free() float64 {
return v.Size - v.Used
}
// The star lets the method change the volume itself
func (v *Volume) Store(tb float64) error {
if tb > v.Free() {
return fmt.Errorf("not enough space on %s", v.Name)
}
v.Used += tb
return nil
}
func main() {
v := Volume{Name: "Archive", Size: 8}
if err := v.Store(5.5); err != nil {
fmt.Println(err)
}
fmt.Println(v.Name, "has", v.Free(), "TB free")
if err := v.Store(4); err != nil {
fmt.Println(err)
}
}
Terminal
$ ./15-methods
Archive has 2.5 TB free
not enough space on ArchiveExercise
Add a method Percent.
TurboShell does not contain Go. These programs are made in Bucket & Code with its Go runtime; the finished file runs on the NAS without Go.