Hello there, GO is awesome !
→ $go version
→ go version go1.9.2 linux/amd64
→ Environment Variables
GOARCH="amd64" GOBIN="" GOEXE="" GOHOSTARCH="amd64" GOHOSTOS="linux" GOOS="linux" GOPATH="/home/no1/go" GORACE="" GOROOT="/usr/local/go" GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64" GCCGO="gccgo" CC="gcc" GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build648036717=/tmp/go-build -gno-record-gcc-switches" CXX="g++" CGO_ENABLED="1" CGO_CFLAGS="-g -O2" CGO_CPPFLAGS="" CGO_CXXFLAGS="-g -O2" CGO_FFLAGS="-g -O2" CGO_LDFLAGS="-g -O2" PKG_CONFIG="pkg-config"
→ Runnable Program
→ Link on Go Play Ground
→ What did you expect to see?
→ I want to know what i’m missing.
→ Is there any other way where i can discuss minor programs than reporting issues after
referring to Documentation/Source Code
→ I’m open for suggestions to help me learn go better (any kind).
→ I thought cap and len would be equal (just before last NOTE print)
→ What did you see instead?
→ A part of Program Output
// …
len : 7 cap : 16
How come the capacity is more than length in this case ?
// …
→ Complete Code :
//
// program.go
// Just started using Go
//
package main
import (
"fmt"
)
func main() {
// Check 1 - Understood how to create slice
fmt.Println("Creating a slice with len 3 and cap 5")
s := make([]byte, 3, 5)
fmt.Println("Printing slice information:")
for in, _ := range s {
s[in] = byte(in)
fmt.Println("At index :", in, "byte value :", s[in])
}
fmt.Println("len : ", len(s), "cap : ", cap(s))
// Check 2 - Understood append function syntax
fmt.Println("Appending 3, 4 as new elements in slice")
s = append(s, 3, 4)
fmt.Println("Printing slice information:")
for in, v := range s {
fmt.Println(in, v)
}
fmt.Println("len : ", len(s), "cap : ", cap(s))
// Check 3 - Trying to check, if append works beyond initial capacity
fmt.Println("Appending 5, 6 as new elements in slice to go out of bound")
s = append(s, 5, 6)
fmt.Println("Printing slice information:")
for in, v := range s {
fmt.Println(in, v)
}
fmt.Println("len : ", len(s), "cap : ", cap(s))
// NOTE :
fmt.Printf("How come the capacity is more than length in this case ?\n cap function is language built-in so, cann't see the source code or documentation to figure out what's going on here ?\n")
}