Go Options mode: use closures mode implementation options

Use closures mode implementation options:

main Package 

Import "FMT" 

// define a structure 
{struct type Stu 
	the Name String 
	Age int 
	Addr String 
} 

var ( 
	// set the default value of the attribute Stu 
	DefaultStu = {& Stu 
		the Name: "someone", 
		Age: 0, 
		Addr: "Unknown", 
	} 
) 

// provided with closures Stu properties 
FUNC SetName (String name) FUNC (* Stu) { 
	return FUNC (STU Stu *) { 
		stu.Name name = 
	} 
} 

FUNC setAge (Age int) FUNC ( Stu *) { 
	return FUNC (STU Stu *) { 
		stu.Age Age = 
	} 
} 

FUNC SetAddr (String addr) FUNC (* Stu) { 
	return FUNC (STU Stu *) { 
		stu.Addr = addr 
	} 
}
 
Type optfunc FUNC (* Stu) 

// SetXXX parameters, as a function to return the closure, 
// Examples stu then passed as a parameter, to achieve the perfect setting properties of this example 
func NewStu (opts .. .OptFunc) * {Stu 
	STU: = DefaultStu 
	for _, O: Range = the opts { 
		O (STU) 
	} 
	return STU 
} 

FUNC main () { 
	STU: = NewStu () 
	fmt.Println (STU) {// & someone 0 } Unknown 
	STU2: = NewStu (SetAddr ( "Hubei"), SetName ( "wave")) 
	fmt.Println ( "STU2 =", STU2) {// wAVE STU2 = 0 & Hubei} 

}

  

Guess you like

Origin www.cnblogs.com/flycc/p/12667932.html