Membuat Golang Struct Menggunakan Fungsi Opsional

sunday-snippet · 27 Okt 2022 · ~2 menit
Sunday Snippet #5 membuat golang struct menggunakan fungsi opsional
Sunday Snippet #5 membuat golang struct menggunakan fungsi opsional

Menggunakan fungsi opsional memungkinkan pengguna untuk mengatur atribut secara opsional

 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
)

// ExampleOptFunc sets Example's optional attribute
type ExampleOptFunc func(*Example)

// WithAttr1 sets Example's OptionalAttr1 as true
func WithAttr1() ExampleOptFunc {
	return func(e *Example) {
		e.OptionalAttr1 = true
	}
}

// WithAttr2 sets Example's OptionalAttr2 as i
func WithAttr2(i int) ExampleOptFunc {
	return func(e *Example) {
		e.OptionalAttr2 = i
	}
}

// WithAttr3 sets Example's OptionalAttr3 as s
func WithAttr3(s string) ExampleOptFunc {
	return func(e *Example) {
		e.OptionalAttr3 = s
	}
}

// Example is an example struct with some optional attributes
type Example struct {
	Name          string `json:"name"`
	OptionalAttr1 bool   `json:"optional_attr1"`
	OptionalAttr2 int    `json:"optional_attr2"`
	OptionalAttr3 string `json:"optional_attr3"`
}

// NewExample creates Example ptr
// requires name
func NewExample(name string, opts ...ExampleOptFunc) *Example {
	e := &Example{
		Name: name,
	}

	for _, opt := range opts {
		opt(e)
	}

	return e
}

// String returns json-encoded string
func (e *Example) String() string {
	var b bytes.Buffer
	enc := json.NewEncoder(&b)
	enc.SetIndent("", "  ")
	_ = enc.Encode(e)
	return b.String()
}

func main() {
	e := NewExample("example",
		WithAttr1(),
		WithAttr2(100),
		WithAttr3("testing"))

	fmt.Println(e)
	// {
	//   "name": "example",
	//   "optional_attr1": true,
	//   "optional_attr2": 100,
	//   "optional_attr3": "testing"
	// }
}
· · ·

Suka Konten Ini?

Bentuk dukungan apapun saya hargai! Dukung saya melalui Bitcoin, Ko-fi, Trakteer, atau lanjut baca konten saya yang lainnya. Kamu bisa menulis respon lewat Webmention dan beritahu saya URLnya lewat Telegraph.

Tulis komentar anda di bawah