Ever needed a custom string type to add your own methods or tweak certain behavior? In languages like Ruby or Javascript, you can directly modify built in types. In other languages, we usually create custom objects to wrap around a default type and then extend that object with necessary methods or attributes.
A sample example in Python would look like:
1 2 3 4 5 6 7 8 9 10 |
class MyString(object): def __init__(self, val): self.val = val def print_len(self): print "Length: " + str(len(self.val)) name = MyString("masnun") name.print_len() |
In Go, we would define a new type based on an existing type. Then define methods on the newly defined type. It allows us to easily create new types based on existing types and then customize to suit our needs. The same example in Go would look like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package main import ( "fmt" ) // create custom_string type based on built in string type custom_string string // method definition - the function "receives" a custom_string type and // acts on the type func (str custom_string) PrintLen() { fmt.Printf("Length: %d \n", len(str)) } func main() { // define a new variable of our new type var name custom_string = "Masnun" // call the custom method name.PrintLen() } |
Simple, isn’t it?