DEV Community

Cover image for First time using Map in Go
ShellRean
ShellRean

Posted on

First time using Map in Go

Every single person has their clean code, but not for team

Everything changes. I was changed my programming language from PHP to Go and I found many differences.

There are things that I interest, one of them is map

var student map[string]string
Enter fullscreen mode Exit fullscreen mode

In PHP we know map as array associative

$student["name"] = "Brian"
Enter fullscreen mode Exit fullscreen mode

Create Map

To create map is simple, in go just use key var
or ":=" it will create var and set type value as data type

// Just declare variable
var student map[string]string
var champion map[int]string

// OR 
student2 := map[string]string{}
champion2 := map[int]string{}

// map[datatype_key]datatype_value
Enter fullscreen mode Exit fullscreen mode

the value can assign as map to, so you can write

var student map[string]map[string]string
Enter fullscreen mode Exit fullscreen mode

in PHP is equal with

$student = [
    "key" => []
]
Enter fullscreen mode Exit fullscreen mode

Assign data to map

To assign data to map just write like below

student := map[string]string{
    "name"    : "Shellrean",
    "address" : "Jakarta",
}
Enter fullscreen mode Exit fullscreen mode

don't forget to add comma (,) at last map item or you cant get error compiler.

Accessing data map

You can use variable[key] to access data from map

fmt.Printf("%s", student["name"]) // Output: shellrean
Enter fullscreen mode Exit fullscreen mode

Map is iterable type so you can make loop.

for key, value := range student {
  fmt.Printf("%s => %s\n", key, value)
}
Enter fullscreen mode Exit fullscreen mode

One thing that you have to remember is map is unorderable so maybe property name at second or address at first in map order.

Deleting data from map

Delete map is simple use delete function

delete(student, "name")
// delete(map_name, key)
Enter fullscreen mode Exit fullscreen mode

Yeah Go is beautiful language, I was used Java, C++, PHP, JavaScript, Dart. Each language have their benefit and have their strong use in. Go is Strong Typing but have interface{} data type for dynamic data type like use in dart language.

Don't stop to learn

Top comments (0)