packagemainimport"fmt"typestruct1struct{i1intf1float32strstring}funcmain(){ms:=new(struct1)ms.i1=10ms.f1=15.5ms.str="Chris"fmt.Printf("The int is: %d\n",ms.i1)fmt.Printf("The float is: %f\n",ms.f1)fmt.Printf("The string is: %s\n",ms.str)fmt.Println(ms)}//Output:
Theintis:10Thefloatis:15.500000Thestringis:Chris&{1015.5Chris}
packagemainimport("fmt""reflect")typeTagTypestruct{// tags
field1bool"An important answer"field2string"The name of the thing"field3int"How much there are"}funcmain(){tt:=TagType{true,"Barak Obama",1}fori:=0;i<3;i++{refTag(tt,i)}}funcrefTag(ttTagType,ixint){ttType:=reflect.TypeOf(tt)ixField:=ttType.Field(ix)fmt.Printf("%v\n",ixField.Tag)}//Output:
AnimportantanswerThenameofthethingHowmuchthereare
packagemainimport"fmt"typeTwoIntsstruct{aintbint}funcmain(){two1:=new(TwoInts)two1.a=12two1.b=10fmt.Printf("The sum is: %d\n",two1.AddThem())fmt.Printf("Add them to the param: %d\n",two1.AddToParam(20))two2:=TwoInts{3,4}fmt.Printf("The sum is: %d\n",two2.AddThem())}func(tn*TwoInts)AddThem()int{returntn.a+tn.b}func(tn*TwoInts)AddToParam(paramint)int{returntn.a+tn.b+param}//Output:
Thesumis:22Addthemtotheparam:42Thesumis:7
packagemainimport("./person""fmt")funcmain(){p:=new(person.Person)// p.firstName undefined
// (cannot refer to unexported field or method firstName)
// p.firstName = "Eric"
p.SetFirstName("Eric")fmt.Println(p.FirstName())// Output: Eric
}
packagemainimport("fmt")typeCamerastruct{}func(c*Camera)TakeAPicture()string{return"Click"}typePhonestruct{}func(p*Phone)Call()string{return"Ring Ring"}typeCameraPhonestruct{CameraPhone}funcmain(){cp:=new(CameraPhone)fmt.Println("Our new CameraPhone exhibits multiple behaviors...")fmt.Println("It exhibits behavior of a Camera: ",cp.TakeAPicture())fmt.Println("It works like a Phone too: ",cp.Call())}//Output:
OurnewCameraPhoneexhibitsmultiplebehaviors...ItexhibitsbehaviorofaCamera:ClickItworkslikeaPhonetoo:RingRing
packagemainimport("fmt")typeLogstruct{msgstring}typeCustomerstruct{Namestringlog*Log}funcmain(){c:=new(Customer)c.Name="Barak Obama"c.log=new(Log)c.log.msg="1 - Yes we can!"// shorter
c=&Customer{"Barak Obama",&Log{"1 - Yes we can!"}}// fmt.Println(c) &{Barak Obama 1 - Yes we can!}
c.Log().Add("2 - After me the world will be a better place!")//fmt.Println(c.log)
fmt.Println(c.Log())}func(l*Log)Add(sstring){l.msg+="\n"+s}func(l*Log)String()string{returnl.msg}func(c*Customer)Log()*Log{returnc.log}//Output:
1-Yeswecan!2-Aftermetheworldwillbeabetterplace!
packagemainimport("fmt")typeLogstruct{msgstring}typeCustomerstruct{NamestringLog}funcmain(){c:=&Customer{"Barak Obama",Log{"1 - Yes we can!"}}c.Add("2 - After me the world will be a better place!")fmt.Println(c)}func(l*Log)Add(sstring){l.msg+="\n"+s}func(l*Log)String()string{returnl.msg}func(c*Customer)String()string{returnc.Name+"\nLog:"+fmt.Sprintln(c.Log)}//Output:
BarakObamaLog:{1-Yeswecan!2-Aftermetheworldwillbeabetterplace!}