Converting an array into a map
[maxwell@MaxwellDBA convertinganarrayintoamap]$ vim array2map.go
[maxwell@MaxwellDBA convertinganarrayintoamap]$ go run array2map.go
0 1 2 3 0: 1
1: -2
2: 14
3: 0
[maxwell@MaxwellDBA convertinganarrayintoamap]$ cat array2map.go
//the required packages and the beginning of the main() function
package main
import (
"fmt"
"strconv"
)
func main() {
// The second part,which implements the core functionality.
// define the array variable and the map veriable
anArray := [4]int{1, -2 , 14, 0}
aMap := make(map[string]int)
length := len(anArray)
// the for loop is used for visiting all the array elements and adding them to map.
// the stronv.Itoa() function converts the index number of array into a string.
for i:= 0; i < length; i++ {
fmt.Printf("%s ",strconv.Itoa(i))
aMap[strconv.Itoa(i)] = anArray[i]
}
for key, value := range aMap { fmt.Printf("%s: %d\n", key, value)}
}
[maxwell@MaxwellDBA convertinganarrayintoamap]$
Bear in mind that if you know that all the keys of a map will be consecutive positive integer numbers, you might consider using an array or a slice instead of a map. In fact, even if the keys are not consecutive, arrays and slices are cheaper data structures than maps, so you might end up with a sparse matrix.
Structures
Use a structure -- the various elements of a structure are called fields.
Note that structures are usually defined at the begining of a program and outside the main() function.
[maxwell@MaxwellDBA structures]$
[maxwell@MaxwellDBA structures]$ vim goStructures.go
[maxwell@MaxwellDBA structures]$ go run goStructures.go
S2= {0 0 Message 2}
P1= {23 12 A message}
P2= {0 0 Message 2}
0: X int = 23
1: Y int = 12
2: Label string = A message
[maxwell@MaxwellDBA structures]$ cat goStructures.go
package main
import (
"fmt"
"reflect"
)
func main(){
// the first part contain the preamble and the definition of a new structure named message.
//The mssage structure has three fields,named X,Y, and Label.
type message struct {
X int
Y int
Label string
}
//The second part uses the message structure to define two new message variables,named p1 and p2.
p1 := message{23, 12, "A message"}
p2 := message{}
p2.Label = "Message 2"
s1 := reflect.ValueOf(&p1).Elem()
s2 := reflect.ValueOf(&p2).Elem()
fmt.Println("S2= ", s2)
//The last part shows how to print all the fields of a structure without knowing their names using a for loop and the Type() function
typeOfT := s1.Type()
fmt.Println("P1=", p1)
fmt.Println("P2=", p2)
for i := 0; i < s1.NumField(); i++ {
f := s1.Field(i)
fmt.Printf("%d: %s ", i, typeOfT.Field(i).Name)
fmt.Printf("%s = %v\n", f.Type(), f.Interface())
}
}
[maxwell@MaxwellDBA structures]$
The lowercase fields do not get exported ;they cannot be used by reflect.Value.Interface() method.
[maxwell@MaxwellDBA structures]$ cp -p goStructures.go goStructuresusex.go
[maxwell@MaxwellDBA structures]$ vim goStructuresusex.go
[maxwell@MaxwellDBA structures]$ go run goStructuresusex.go
S2= {0 0 Message 2}
P1= {23 12 A message}
P2= {0 0 Message 2}
0: x panic: reflect.Value.Interface: cannot return value obtained from unexported field or methodgoroutine 1 [running]:
panic
:0
reflect.valueInterface
:0
reflect.Value.Interface
:0
main.main
/home/maxwell/goproject/structures/goStructuresusex.go:42
__start_context
:0
exit status 2
[maxwell@MaxwellDBA structures]$ cat goStructuresusex.go
package mainimport (
"fmt"
"reflect"
)
func main(){
// the first part contain the preamble and the definition of a new structure named message.
//The mssage structure has three fields,named X,Y, and Label.type message struct {
//X int
// test lowercase fields
x int
Y int
Label string}
//The second part uses the message structure to define two new message variables,named p1 and p2.
p1 := message{23, 12, "A message"}
p2 := message{}
p2.Label = "Message 2"s1 := reflect.ValueOf(&p1).Elem()
s2 := reflect.ValueOf(&p2).Elem()
fmt.Println("S2= ", s2)//The last part shows how to print all the fields of a structure without knowing their names using a for loop and the Type() function
typeOfT := s1.Type()
fmt.Println("P1=", p1)
fmt.Println("P2=", p2)
for i := 0; i < s1.NumField(); i++ {
f := s1.Field(i)
fmt.Printf("%d: %s ", i, typeOfT.Field(i).Name)
fmt.Printf("%s = %v\n", f.Type(), f.Interface())
}}
[maxwell@MaxwellDBA structures]$
Interfaces
Interfaces are an advanced Go feature, which means that you might not want to use them in your programs if you are not feeling very comfortable with Go.
Interfaces can be very practical when developing big Go program, which is the main reason for talking about interfaces in this book.
Interfaces are abstract types that define a set of functions that need to be implemented so that a type can be considered an instance of the interface.So an interfaces is two things -- a set of methods and a type
[maxwell@MaxwellDBA Interfaces]$ vim interfaces.go
[maxwell@MaxwellDBA Interfaces]$ vim interfaces.go
[maxwell@MaxwellDBA Interfaces]$ go run interfaces.go
{-1 12}
X: -1 Y: 12
X: 10 Y: 0
[maxwell@MaxwellDBA Interfaces]$ cat interfaces.go
package main
import (
"fmt"
)
type coordinates interface {
xaxis() int
yaxis() int
}
type point2D struct {
X int
Y int
}
// define an interface called coordinates and a new structure called point2D.
func (s point2D) xaxis() int {
return s.X
}
func (s point2D) yaxis() int {
return s.Y
}
func findCoordinates(a coordinates) {
fmt.Println("X:", a.xaxis(), "Y:", a.yaxis())
}
type coordinate int
func (s coordinate) xaxis() int {
return int(s)
}
func (s coordinate) yaxis() int {
return 0
}
func main() {
x := point2D{X: -1, Y: 12}
fmt.Println(x)
findCoordinates(x)
y := coordinate(10)
findCoordinates(y)
}
[maxwell@MaxwellDBA Interfaces]$
Creating random numbers
Random numbers have many uses, including:
- the generation of good passwords as well as the creation of files with random data that can be used for testing other applications.
- bear in mind that usually programming languages generate pseudorandom numbers that approximate the properties of a true random number generator.
Go uses the math / rand package for generating random numbers and needs a seed to start producing random numbers.
[maxwell@MaxwellDBA randomnumber]$ vim random.go
[maxwell@MaxwellDBA randomnumber]$ go run random.go 12 32 20
16 25 14 14 17 29 19 23 18 24 24 21 27 30 19 19 21 17 13 15
[maxwell@MaxwellDBA randomnumber]$ cat random.go
package main
import (
"fmt"
"math/rand"
"os"
"strconv"
"time"
)
func random(min, max int) int {
return rand.Intn(max-min) + min
}
func main() {
MIN := 0
MAX := 0
TOTAL := 0
if len(os.Args) > 3 {
MIN, _ = strconv.Atoi(os.Args[1])
MAX, _ = strconv.Atoi(os.Args[2])
TOTAL, _ = strconv.Atoi(os.Args[3])
} else {
fmt.Println("Usage:", os.Args[0], "MIN MAX TOTAL")
os.Exit(-1)
}
rand.Seed(time.Now().Unix())
for i := 0; i < TOTAL; i++ {
myrand := random(MIN, MAX)
fmt.Print(myrand)
fmt.Print(" ")
}
fmt.Println()
}
[maxwell@MaxwellDBA randomnumber]$
you should use the crypto/rand package, which implements a cryptographically secure pseudorandom number generator. You can find more information about the crypto/rand package by visiting its documentation page at https://golang.org/pkg/crypto/rand/