Skip to content

Instantly share code, notes, and snippets.

@Ikhan
Created August 27, 2023 03:27
Show Gist options
  • Save Ikhan/eb60bb4eafd3dd5cb26cf0ee63506204 to your computer and use it in GitHub Desktop.
Save Ikhan/eb60bb4eafd3dd5cb26cf0ee63506204 to your computer and use it in GitHub Desktop.
functional options (pattern)
package main
import "fmt"
type UserProfile struct {
username string
email string
age int
avatarURL string
}
type ProfileOption func(profile *UserProfile) error
func Username(name string) ProfileOption {
return func(profile *UserProfile) error {
//some valiadtion can apply
profile.username = name
return nil
}
}
func Email(e string) ProfileOption {
return func(profile *UserProfile) error {
//some valiadtion can apply
profile.email = e
return nil
}
}
func Age(a int) ProfileOption {
return func(profile *UserProfile) error {
//some valiadtion can apply
profile.age = a
return nil
}
}
func avatarURL(avatar string) ProfileOption {
return func(profile *UserProfile) error {
//some valiadtion can apply
profile.avatarURL = avatar
return nil
}
}
func NewUserProfile(opts ...ProfileOption) (*UserProfile, error) {
profile := &UserProfile{}
for _, opt := range opts {
err := opt(profile)
if err != nil {
return nil, err
}
}
return profile, nil
}
func main() {
// eg
user, err := NewUserProfile(Username("bob"), Email("[email protected]"), avatarURL("http://example.com/1.jpeg"))
if err != nil {
}
fmt.Println(user)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment