58

From PHP to Go: Arrays

 5 years ago
source link: https://www.tuicool.com/articles/hit/RrmuMfv
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

This is a quick and dirty article about arrays, slices, and maps in Go for all those who come from PHP and are getting started with this fantastic language.

Table of contents

1. The basics

There are two essential things you must know:

  1. In Go, you have three kinds of similar structures to PHP arrays: arrays , slices , and maps . We will see the difference later.
  2. In Go, the elements of an array have the same type . This type must be defined when you declare the variable for this array/slice/map.

The main difference between those kinds of structures is if the length of the array is fixed or not and if they have Key/Value pairs.

Array Slice Maps Length Fixed Variable Variable Key/Value No No Yes

2. Arrays in Go

Let's say we want to declare an array of type string to save the days of the week:

week := [7]string{"Sunday", "Monday", "Tuesday", .., "Saturday"}

See how there is a seven between the brackets indicating the number of elements it will contain. Once it is declared, you can't change the number of items on it, but you can change the values.

week[1] = "New Monday"  // This will work. "Monday" is now "New Monday"
week[8] = "New Day"     // This will fail, we are out of bounds.
week[1] = 1             // This will fail, cannot use type int as type string

Arrays as such are rarely used in Go due to their fixed length.

3. Slices in Go

Slices work like arrays as explained above, but they have variable length.

For declaring the same array as above, but as a slice, we simply omit the number between the brackets:

week := []string{"Sunday", "Monday", "Tuesday", .., "Saturday"}

Since there is no fixed length, we can append new items to the slice:

week[8] = "New Invented Day" // This will work, since there are no bounds
weeks = append(weeks, "New Invented Day") // We can also use the method append()

And we can also delete items from the slice. If we want to remove the item of index 1 ("New Monday"):

weeks = append(week[:1], week[2:]...)

Note that, as in the code above, we can get some items of any slice (and arrays) using the brackets after the variable :

week[4:6] // This will return ["Friday", "Saturday"]

To know the number of elements in any slice, use the function `len()`

numberOfDays := len(week)

## 4. Maps in Go If you need to use key/value pairs, then you need to use maps. For instance, if you need to replicate this PHP array in Go:

<?php 
    $products = [
        "Cap" => "Red", 
        "T-Shirt" => "Blue"
    ]; 
?>

You would need to define a map of key type string and value type string. You can use one of those ways:

products := make(map[string]string) 
products := map[string]string{}
products := map[string]string{ 
    "Cap":     "Red", 
    "T-Shirt": "Red",
}

Since now we have key/value pairs, you can append elements without using append:

products["Pants"] = "Blue"

## 5. Iterate over arrays, slices, and maps in Go The most common way is to use `range`

for key,value := range products {
    fmt.Printf("Key: %s Value: %s\n", key, value)
}

## 6. Subarrays with different types What if I need an array of arrays, also with variables of different type, like I can do on PHP? You can create "maps of maps". For instance, let's say you need to have this PHP array in Go:

<?php 
    $products = [
        "Cap" => [
            "Color" => "Red",
            "Size" => "XL"
        ],
        "T-Shirt" => [
            "Color" => "Blue",
            "Size" => "XS"
        ]
    ];
?>

You could create such a map doing this:

products := make(map[string]map[string]string)
If you need to have different variables of different type in your subarrays, you need to define new variable types using structs

:

type Property struct {
  Color string
  Size string
  Price int
}

products := make(map[string]Property)

products["Cap"] = Property{
        Color: "Red",
        Size: "XL", 
        Price: 30,
}

That's all Folks! ;)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK