Post

Visualizzazione dei post da gennaio, 2016

Method Expressions

A method is a function associated to a type. The Go method declaration is a variation of a function declaration in which a initial parameter appears before the method name. The parameter has the type of the object designed to receive the method or is a pointer of that type. In this example the type Order has two methods, the AddProduct and the CalculateTotalCost . type Order struct {      Id int32      ProductList [] Product } func ( o * Order ) AddProduct( p Product ) {      o . ProductList = append ( o . ProductList , p ) } func ( o * Order ) CalculateTotalCost() ( cost float32 ) {      for _ , p := range o . ProductList {          cost += p . Price      }      return } We can call a method on an instance of the type Order or we can use a method value o := Order { Id : 1 }      o . AddProduct ( Product { Id : 1 , Name : "milk" , Price : 1.1 })      // method