Tag: tutorial

  • Get GOing; learning Go continued

    Picking back up with learning Go. Starting with Arrays.

    I have to admit, this will be a hard switch from PHP. When I create arrays in PHP, generally, I try to be as explicit as possible by using associative arrays so I can pull the information I want back out:

    <?php
    
    $new_array = array(
       'name' => 'Jane',
       'favorite_color' => 'Red',
       'favorite_fruit' => 'Apple',
    );
    
    ?>
    

    It doesn’t appear that Go has this option. If I wanted to create the same array in Go, it would look like this:

    package main
    import ("fmt")
    
    func main() {
      var new_array = [3]string{'Jane','Red','Apple'}
    
      fmt.Println(new_array)
    }
    

    Coming from a PHP perspective, this seems complicated because it means that I have to remember the order in which I input information to get the correct data out. This is a hassel. In PHP, I just have to remember that if I want a name, I would fetch $new_array['name']. In Go, this would have to be new_array[1] which isn’t as explicit.

    However, I think the reason behind this limitation is, in itself, a concept switch about how to use arrays. In PHP, arrays are a veritable Mary Poppins bag which can handle multiple data types, be deeply nested, and have items added or removed without consequence (until you need it). However, this can be a trap. If you haven’t thought through the structure of your data (for example, by creating a class object), it can be tempting to just throw everything in your array-bag. Longterm, this can cause your code to spaghetti out of control and be a performance pain.

    Go seems to seek to avoid this trap by requiring that all items in an array be of the same data type. There is also a built in method to control how many items should be placed within an array. In this way, arrays seems to be more like glass recycling bins in Germany.

    The bins only take one type of material, glass, it is sorted by color, and you can see when the bin is full. It doesn’t matter as much what order things are in because you know everything in the “brown glass” bin is a type of brown glass.

    Photo credit https://www.archer-relocation.com/how-to-recycle-in-germany/

    package main
    import ("fmt")
    
    func main() {
      var zipcodes = [3]int{ 10011, 90210, 20001 }
      var colors = [3]string{ 'red', 'blue', 'green' }
      var fruits = [3]string{ 'apples', 'oranges', 'cherries' }
    
      fmt.Println(zipcodes)
      fmt.Println(colors)
      fmt.Println(fruits)
    }
    

    This is the key point of the concept switch; in PHP arrays can be used as a catch all (even if it isn’t necessarily a good idea) and in Go arrays are used to catch a specific type of data with a grouped theme so you don’t care as much about the order of items. It almost seems like in PHP, it is easier to focus on where you need a collection of data because you can push so much into a single array (e.g. I am going to throw everything in my bag so I have it with me). In Go, a dev is required to think more about what you need since it makes more sense to group themed items together (e.g. I am going to use suitcase cubes to make sure its nice and neat).

    PHP Arrays

    <?php
    // Let's describe Mary Poppins in an array
    
    $mary_poppins = array(
       'height' => 'average',
       'singing' => 'often',
       'bag_items' => array( 'lamp', 'umbrella', 'spoonful of sugar'),
       'cleanliness' => 'strict',
       'hair' => 'brown',
    );
    ?>
    

    GO Arrays

    package main
    import ("fmt")
    
    func main() {
       // Let's describe Mary Poppins in a series of arrays
      var physical_traits = [2]string{ 'brown hair', 'average height'}
      var talents = [2]string{ 'cleaning', 'singing'}
      var bag_contents = [3]string{ 'lamp', 'umbrella', 'spoonful of sugar'}
    }
    

    Now, I don’t want to give the impression there isn’t any structure to Go arrays. It is based on the index of the array (which starts at 0).

    For example, let’s say you are running a competition. The competitors have to face off in a way that you know who got last place before you know who got first. Let’s set up an array to store where each competitor placed:

    package main
    import ("fmt")
    
    var winners_names = [6]string{}
    
    func main() {
      fmt.Println(winners_names)
    }
    

    Calling main() would result in printing [ "" "" "" "" "" "" ]. It is an empty array of strings. Now, let’s add a function to update the winners names as we receive them.

    package main
    import ("fmt")
    
    var winners_names = [6]string{}
    
    func main() {
      fmt.Println(winners_names)
    }
    
    func record_winner( place, name) {
       // Remember that indexes start with 0, so 6th place would actually be stored at winners_names[5]
       var index = place - 1 
       winners_names[index] = [name]
    }
    

    I think this syntax would work (haven’t got to writing functions yet 😅). So, when we found out that the first two competitors won 5th and 6th place, we could call record_winner() to update the winners_name list.

    record_winner( 5, 'Jane Doe')
    record_winner( 6, 'John Doe')
    

    Now, when we call main(), the output would be [ "" "" "" "" "Jane Doe" "John Doe" ]. You could repeat this until all of the placements are filled in.

    So this is really useful when you have a situation where the ranking of an item can match the order in which it needs to be displayed.

    Stopping here for today. I’ll pick this up next week with how to slice and dice things.