Collections in Go
| Collection | Description |
|---|---|
| Array [n]T |
fixed-size collection of elements of the same type. Array cannot be
resized
|
|
Slices [] (Dynamic Array) = C++(vector<int>) = Rust(vec<i32>) |
What is slice? Slice is part of an array.Changing the
elements of a slice modifies underlying array. Slice has 3 components? 1. Pointer(to underlying array) 2. Length(number of elements in slice). len(slice) 3. Capacity(maximum number of elements it can hold). cap(slice): length of undelying array - 1 nil slice: slice which does not point to any array(at present), but can in future. Creating slice using make(): Preallocate memory for slice and assign later
|
Channels
Queue(Implemented using slice)
package main
import "fmt"
type test struct { //Declare a struct having slice which will act as queue
q []int
}
func Constructor() test {
return test{}
}
func (this *test) Push(x int) {
this.q = append(this.q, x) //Push() append x to queue
}
func (this *MyStack) Pop() {
this.q = this.q[1:] //Pop() Remove 1st element
}
func (this *MyStack) Top() int {
return this.q[0] //Top()
}
func (this *MyStack) Empty() bool { //Size()
if len(this.q) == 0 {
return true
}
return false
}
Stack using slice
(struct = class)
-
Class is defined as struct type. Example: Person is defined of type
struct.
The struct type can be considered similar to a class, as it allows you to define fields and associated methods.
package main
import "fmt"
type student struct { // Define a struct type
name string
age int
marks []int // slice = dynamic ints
misc []interface{} // misc is a slice that can hold values of any type
}
// Define a method associated with the Person struct
// To associate a method with a struct, define a method with a receiver type that matches the struct type.
func (p Person) SayHello() {
fmt.Printf("Hello, my name is %s and I am %d years old.\n", p.name, p.age)
}
func main() {
// Create a new instance of Person
person := Person{name: "John", age: 30}
// Call the SayHello method
person.SayHello()
}