Contents

golang functional-options

Functional Options

go语言的函数没有重载以及默认参数的功能,这个时候生成一个i对象会变得极其麻烦

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
type Person struct{
    Name string
    Age  int
    Country string
    Gender  string
    Height  string
    Address string
}
func main(){
    person :=Person{
        Name:"张三",
        Age: -1
        Country: "China",
        Gender: "Male",
        Height: "-1",
        Address: "unknown",
    }
}

我们可以使用函数式选项来解决这一问题。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
type Person struct {
    Name    string
    Age     int
    Country string
    Gender  string
    Height  string
    Address string
}

// 将func(*Person)这种类型的函数简化命名
type per func(*Person)

func Country(country string) per {
    return func(person *Person) {
        person.Country = country
    }
}

func Gender(gender string) per{
    return func(person *Person){
        person.Gender = gender
    }
}

func Gender(gender string) per{
    return func(person *Person){
        person.Gender = gender
    }
}

func Address(address string) per{
    return func(person *Person){
        person.Address = address
    }
}

// NewPerson ...
func NewPerson(name string,ops ...per) *Person {
    person := &Person{
        Name: name,
        Age: -1,
        Country: "China",
        Gender: "Male",
        Height: 0,
        Address: "unknown",
    }

    for _,op:= range ops {
        op(person)
    }
    return person
}

用法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package main

import (
    "fmt"
    op "studygo/pattern/functionOptions"
)

// main ...
func main() {
    person1 := op.NewPerson("zhangsan")
    fmt.Println(person1)
    person2 := op.NewPerson("Marry", op.Gender("Female"), op.Country("Japan"))
    fmt.Println(person2)
}