我想知道Go中相當于C 函式系結默認引數的最佳做法,這可能是用戶最容易看到的函式引數(有linter幫助)。 你認為什么才是最符合GO風格、最容易使用的測驗函式呢?
C 中的一個函式例子:
void test(int x, int y=0, color=Color()>。
圍棋中的等價交換
1. 有多個簽名:func test(x int)>
func testWithY(x int, y int)
func testWithColor(x int, color Color)
func testWithYColor(x int, y int, color Color)
專業:
- linter將顯示所有測驗的可能性 編譯器將采取最短的路徑。
缺點:
- 當有大量的引數時,可能會被淹沒 。
2.使用結構引數:
type testOptions struct {
X int int
Y int int
顏色 顏色
}
func test( opt *testOptions)
//user
test(&testOptions{x: 5})
專業:
- 僅有一個簽名
- 可以只指定一些值 。
缺點:
- 需要定義一個結構 這些值將由系統默認設定。
在github.com/creasty/defaults模塊的幫助下,有一種方法可以設定默認值(但代價是在運行時呼叫反射)。
type testOptions struct {
X int int
Y int `default: "10"`
color 顏色 `default:"{}"`/span>
}
func test(opt *testOptions) *hg。 Node {
if err := defaults.Set(opt); err != nil {
panic(err)
}
專業:
- 設定默認值
缺點:
- 在運行時使用reflect 。
P.S: 我看到了使用變數引數
...或/用interface{},但我發現不容易知道使用哪個引數(或者也許有一種方法可以向linter表明引數串列)。
uj5u.com熱心網友回復:
兩種方式都可以正常作業,但在Go中,功能選項模式可能更適合于實作這種功能。
它是基于接受可變數量的WithXXX型別的函式引數的想法,這些引數擴展或修改了呼叫的行為。
type Test struct {
X int int
Y int int
顏色 顏色
}
type TestOption func(*Test)
func test(x int, opts ... TestOption){
p := &Test{
X: x,
Y: 12,
顏色:defaultColor。
}
for _, opt := range opts {
opt(p)
}
p.runTest()
}
func main() {
test(12)
test(12, WithY(34)
test(12, WithY(34), WithColor(Color{1, 2, 3})
}
func WithY(y int) TestOption {
return func(p *Test) {
p.Y = y
}
}
func WithColor(c Color) TestOption {
return func(p *Test) {
p.color = c
}
uj5u.com熱心網友回復:
我認為,如果結果只是少數幾個函式,你的選項1是一個很好的習慣性選擇。我也認為功能選項模式是一個不錯的選擇,它經常被用于工廠函式中。
為了增加另一個選擇,這個問題可能表明代碼需要重新構造。test()應該是一個知道可選引數的型別上的方法嗎?
go諺語之一是 "讓零值有用",所以一個型別的零值被認為是指使用默認值。如果0是你的int型別的有效值,那么考慮*int,重點是避免參考你想保留默認值的欄位。
package main
import (
"fmt"/span>
)
const (
defaultY = 10 const (
defaultColor = "blue" (
)
type Color string
type Thing struct {
Yint
顏色 顏色
}
func (t Thing) getY() int {
if t.Y == 0 {
return defaultY
}
return t.Y
}
func (t Thing) getColor() Color {
if t.Color == ""/span> {
return defaultColor
}
return t.Color
}
func (t Thing) Test(x int) {
fmt.Println(x, t.getY(), t.getColor())
}
func main() {
Thing{}.Test(12)
Thing{Y: 11}.Test(12)
Thing{Y: 11, Color: "red"}.Test(12)
}
//12 10 blue。
//12 11 blue //12 11 blue?
//12 11 red //12 11 red
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/329362.html
標籤:
