常見golang的struct賦值有兩種:
1)定義變數同時初始化
val := &Options{UID:int(1), }
2)先定義變數,再賦值
val := new(Options)val.UID = int(3)
賦值設計模式:
1)每個屬性一個方法,方法名稱與屬性有關
2)賦值方法的傳回值是統一的,可由同一個方法無差異執行
package mainimport ("os")func main() {//err := New("/tmp/empty.txt")//if err != nil {//panic(err)//}err := New("/tmp/file.txt", Length(200), UID(1000), Contents("Lorem Ipsum Dolor Amet"))if err != nil {panic(err)}}
// 結構體定義type Options struct {UID intGID intFlags intContents stringPermissions os.FileModeLength int}
// 賦值方法約束,介面型函數(介面只有一個函數,介面型函數解決很完美,沒必要單獨定義介面並實現)type Option func(*Options)
// 其中一個屬性的賦值函數func UID(userID int) Option {return func(args *Options) {args.UID = userID}}func Length(Length int) Option {return func(args *Options) {args.Length = Length}}func GID(groupID int) Option {return func(args *Options) {args.GID = groupID}}func Contents(c string) Option {return func(args *Options) {args.Contents = c}}func Permissions(perms os.FileMode) Option {return func(args *Options) {args.Permissions = perms}}// 建立對象唯一入口func New(filepath string, setters ...Option) error {// 建立預設值對象args := &Options{UID: os.Getuid(),GID: os.Getgid(),Contents: "",Permissions: 0666,Flags: os.O_CREATE | os.O_EXCL | os.O_WRONLY,}// 賦值操作for _, setter := range setters {setter(args)}// 對象其他初始化操作f, err := os.OpenFile(filepath, args.Flags, args.Permissions)if err != nil {return err} else {defer f.Close()}if _, err := f.WriteString(args.Contents); err != nil {return err}return f.Chown(args.UID, args.GID)}