Array and Slices
Go has a built-in type called array
for representing fixed-length sequences of values. An array is declared using the [size]type
syntax, where size
is the number of elements in the array and type
is the type of each element. For example:
var a [3]int
a[0] = 1
a[1] = 2
a[2] = 3
You can also use the :=
operator to declare and initialize an array in one line:
b := [3]int{1, 2, 3}
You can access and modify the elements of an array using the index operator [index]
. The indices of an array start at 0 and go up to size-1
. Go also has a built-in type called slice
, which is a variable-length sequence of values. A slice is created by specifying a start and end index of an array or another slice. For example:
c := a[1:3]
This creates a new slice c
that contains the elements at indices 1 and 2 of the array a
. You can also use the make
function to create a slice with a specified length and capacity. The length is the number of elements in the slice, and the capacity is the maximum number of elements that can be stored in the underlying array. For example:
d := make([]int, 3, 5)
This creates a new slice d
with length 3 and capacity 5. You can use the len
and cap
functions to get the length and capacity of a slice, respectively. You can append elements to a slice using the append
function. For example:
d = append(d, 4)
d = append(d, 5)
This will append the elements 4 and 5 to the end of the slice d
. If the underlying array is not large enough to accommodate the new elements, a new array will be allocated and the elements will be copied over.
Maps
Go has a built-in type called map
for storing key-value pairs. A map is created using the make
function and the map
type, and elements are added using the index operator [key] = value
. For example:
m := make(map[string]int)
m["one"] = 1
m["two"] = 2
This creates a new map m
with string keys and int values. You can access and modify the elements of a map using the index operator [key]
. You can also use the :=
operator to declare and initialize a map in one line:
n := map[string]int{"one": 1, "two": 2}
You can use the delete
function to remove an element from a map:
delete(n, "one")
You can use the len
function to get the number of elements in a map. You can iterate over the keys and values of a map using a range
loop:
for k, v := range m {
fmt.Println(k, v)
}
This will print the key and value of each element in the map m
. Example: Here is an example of using maps in Go:
package main
import "fmt"
func main() {
m := make(map[string]int)
m["one"] = 1
m["two"] = 2
n := map[string]int{"one": 1, "two": 2}
delete(n, "one")
fmt.Println(len(m))
fmt.Println(len(n))
for k, v := range m {
fmt.Println(k, v)
}
}
Output:
2
1
one 1
two 2
Structs
Go has a built-in type called struct
for defining composite data types. A struct is a collection of fields, each with a name and a type. For example:
type Point struct {
X int
Y int
}
This defines a new struct type Point
with two fields X
and Y
, both of type int
. You can create a new struct value using the struct
keyword and the field values:
p := Point{1, 2}
You can access and modify the fields of a struct using the dot operator .
:
p.X = 3
fmt.Println(p.Y)
You can also use the new
function to create a pointer to a struct value:
q := new(Point)
q.X = 4
q.Y = 5
In this case, q
is a pointer to a Point
struct value. You can define methods on structs by specifying a receiver type. A method is a function with a special receiver argument that is bound to the struct. For example:
func (p *Point) Distance() float64 {
return math.Sqrt(float64(p.X*p.X + p.Y*p.Y))
}
This defines a method Distance
on the Point
struct type with a receiver type of *Point
. The method returns the distance of the point from the origin using the Pythagorean theorem. You can call a method on a struct value or a pointer to a struct value using the dot operator:
fmt.Println(p.Distance())
fmt.Println(q.Distance())
This will print the distance of the points p
and q
from the origin. Example: Here is a complete example of using structs and methods in Go:
package main
import (
"fmt"
"math"
)
type Point struct {
X int
Y int
}
func (p *Point) Distance() float64 {
return math.Sqrt(float64(p.X*p.X + p.Y*p.Y))
}
func main() {
p := Point{1, 2}
q := new(Point)
q.X = 4
q.Y = 5
fmt.Println(p.Distance())
fmt.Println(q.Distance())
}
Output:
2.23606797749979
6.4031242374328485
Working with JSON and XML in GO
Go has built-in support for encoding and decoding JSON data through the encoding/json
package.
To encode a value as JSON, you can use the Marshal
function from the json
package:
type User struct {
Name string
Age int
}
user := User{"Alice", 20}
data, err := json.Marshal(user)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(data))
This encodes the user
struct as a JSON object and prints it as a string. The Marshal
function returns a byte slice containing the JSON data and an error value. You should check the error value to handle any errors that may occur during marshaling. To decode a value from JSON, you can use the Unmarshal
function from the json
package:
var user User
err := json.Unmarshal(data, &user)
if err != nil {
log.Fatal(err)
}
fmt.Println(user.Name)
This decodes the JSON data into the user
struct and prints the value of the Name
field. The Unmarshal
function takes a byte slice containing the JSON data and a pointer to the value to be decoded. You can also use the json.Encoder
and json.Decoder
types to stream JSON data. For example:
type User struct {
Name string
Age int
}
func main() {
// Encode
user := User{"Alice", 20}
encoder := json.NewEncoder(os.Stdout)
encoder.Encode(user)
// Decode
decoder := json.NewDecoder(os.Stdin)
var user2 User
decoder.Decode(&user2)
fmt.Println(user2.Name)
}
This example encodes the user
struct to os.Stdout
and decodes a JSON object from os.Stdin
into the user2
struct.
Handling JSON data in Go is easy and efficient using the built-in json
package. You can use the Marshal
and Unmarshal
functions to convert between JSON data and Go values, and the json.Encoder
and json.Decoder
types to stream JSON data. You should always check the error values returned by these functions to handle any errors that may occur.
Working with XML
Go has built-in support for encoding and decoding XML data through the encoding/xml
package.
To encode a value as XML, you can use the Marshal
function from the xml
package:
type User struct {
XMLName xml.Name `xml:"user"`
Name string `xml:"name"`
Age int `xml:"age"`
}
user := User{xml.Name{"", "", "user"}, "Alice", 20}
data, err := xml.Marshal(user)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(data))
This encodes the user
struct as an XML element and prints it as a string. The Marshal
function returns a byte slice containing the XML data and an error value. You should check the error value to handle any errors that may occur during marshaling. To decode a value from XML, you can use the Unmarshal
function from the xml
package:
var user User
err := xml.Unmarshal(data, &user)
if err != nil {
log.Fatal(err)
}
fmt.Println(user.Name)
This decodes the XML data into the user
struct and prints the value of the Name
field. The Unmarshal
function takes a byte slice containing the XML data and a pointer to the value to be decoded. You can also use the xml.Encoder
and xml.Decoder
types to stream XML data. For example:
type User struct {
XMLName xml.Name `xml:"user"`
Name string `xml:"name"`
Age int `xml:"age"`
}
func main() {
// Encode
user := User{xml.Name{"", "", "user"}, "Alice", 20}
encoder := xml.NewEncoder(os.Stdout)
encoder.Encode(user)
// Decode
decoder := xml.NewDecoder(os.Stdin)
var user2 User
decoder.Decode(&user2)
fmt.Println(user2.Name)
}