Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialtheteamtreehouse
3,472 PointsCan you place restrictions on custom types?
For example, Hour cannot be greater than 24 or less than 0, etc.
1 Answer
Liam Clarke
19,938 PointsHello
You can add a method to your custom type to check its validity. Here's an example below:
package main
import "fmt"
// Minutes is the number of minutes in an hour.
type Minutes int64
// Valid will check that the int provided is valid.
func (m Minutes) Valid() bool {
return m > 0 && m <= 60
}
func main() {
mins := Minutes(42)
if ok := mins.Valid(); !ok {
fmt.Printf("Minutes are invalid: Expected between 0 and 60, found %d", mins)
return
}
fmt.Printf("Valid minutes can now be used: %d", mins)
}