I have been a C/C++ developer for more than a decade and now getting a chance to work in Go. There are many past references of C, C++, and Python to learn the language quickly. but there are some new syntax that appear unfamiliar. We share such language specific nuances, used widely in production quality code, to help us browsing Golang code.
Methods
- A method is similar to a member function of a class (user defined type).
package main
import "fmt"
type Node struct {
val int64
}
// Returns a pointer of Node type
//
func (n *Node) addNode() *Node {
newNode := new(Node)
newNode.val = 10
return newNode
}
func main() {
n := &Node {10}
m := n.addNode()
fmt.Print(m)
}
A sample program of a linked list in Go with comments explaining the code.
package main
import "fmt"
type Node struct {
prev *Node
next *Node
// key can assume any standard type
key interface{}
}
type List struct {
head *Node
tail *Node
}
// A method defined for type List, returns nothing
// and accepts a key
//
func (L *List) Insert(key interface{}) {
// Create a new node with 'next' pointing
// to Head. The 'prev' is by default zero.
//
list := &Node{
next: L.head,
prev: nil,
key: key,
}
// Attaching the new node at the head by
// updating prev of current head to the
// newly created node.
//
if L.head != nil {
L.head.prev = list
}
// List is the first node so prev is nil
list.prev = nil
// Update the head
L.head = list
l := L.head
// Now find the last node and update its tail link
// to the newly added node.
//
for l.next != nil {
l = l.next
}
L.tail = l
fmt.Printf("head->%d\n", L.head.key)
fmt.Printf("tail->%d\n", L.tail.key)
}
// Another method defined for type List
//
func (l *List) Display() {
list := l.head
for list != nil {
fmt.Printf("%+v->", list.key)
list = list.next
}
fmt.Println()
}
// A function defined for type List
//
func Display(l *List) {
list := l.head
for list != nil {
fmt.Printf("%+v->", list.key)
list = list.next
}
fmt.Println()
}
func main() {
link := List{}
link.Insert(1)
link.Insert(2)
link.Insert(3)
link.Insert(4)
link.Insert(5)
// Calling a method
link.Display()
// Calling a function
Display(&link)
}
References
Written with StackEdit.