Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary in Go

I'm just starting out with Go, and coming from Python I'm trying to find the equivalent of a dict in Python. In Python I would do this:

d = {
    'name': 'Kramer',  # string
    'age': 25          # int
}

I first found the map type, but that only allows for one type of value (it can't handle both ints and strings. Do I really need to create a struct whenever I want to do something like this? Or is there a type I'm missing?

like image 273
kramer65 Avatar asked Sep 05 '17 17:09

kramer65


People also ask

Are there dictionaries in Go?

Go provides a very convenient implementation of a dictionary by its built-in map type. In this article I'll enrich the map built-in type with some convenient operations to get information out of it, and to change its content.

What are maps in Go?

Maps are used to store data values in key:value pairs. Each element in a map is a key:value pair. A map is an unordered and changeable collection that does not allow duplicates. The length of a map is the number of its elements.

How do you check if a key exists in map in Golang?

Check if Key is Present in Map in Golang To check if specific key is present in a given map in Go programming, access the value for the key in map using map[key] expression. This expression returns the value if present, and a boolean value representing if the key is present or not.


2 Answers

Basically the problem is that it's hard to encounter a requirement to store values of different types in the same map instance in real code.

In your particular case, you should just use a struct type, like this:

type person struct {
  name string
  age  int
}

Initializing them is no harder than maps thanks to so-called "literals":

joe := person{
  name: "Doe, John",
  age:  32,
}

Accessing individual fields is no harder than with a map:

joe["name"] // a map

versus

joe.name // a struct type

All in all, please consider reading an introductory book on Go along with your attemps to solve problems with Go, as you inevitably are trying to apply your working knowledge of a dynamically-typed language to a strictly-typed one, so you're basically trying to write Python in Go, and that's counter-productive.

I'd recommend starting with The Go Programming Language.

There are also free books on Go.

like image 118
kostix Avatar answered Oct 24 '22 23:10

kostix


That's probably not the best decision, but you can use interface{} to make your map accept any types:

package main

import (
    "fmt"
)

func main() {
    dict := map[interface{}]interface{} {
        1: "hello",
        "hey": 2,
    }
    fmt.Println(dict) // map[1:hello hey:2]
}
like image 34
skovorodkin Avatar answered Oct 24 '22 22:10

skovorodkin