Created
August 27, 2023 03:27
-
-
Save Ikhan/eb60bb4eafd3dd5cb26cf0ee63506204 to your computer and use it in GitHub Desktop.
functional options (pattern)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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