I am trying to rewrite go code to python and I don’t understand how the make() function in Golang works.
As an example I have this code which I’m trying to rewrite to Python:
a = make([]string, 1)
b = make([]int, 1)
c = make(map[string]string)
Any help is appreciated.
>Solution :
No need to make anything in Python… or in other words, no need to write a function that mimics make. Unlike Go where you have to be explicit about allocating something, in Python this is implicit as objects are allocated automatically on creation for you.
a = make([]string, 1): this is a slice ofstringof size 1 and capacity 1, in Python you can just create an empty list instead:a = []and then.append()strings into it. Unlike Go for slices or arrays, Python does not require all elements of a list to be of the same type. If you want you could createa = [None]just to be able to index the list right away (in generala = [default_value] * size).b = make([]int, 1): same here, justb = []orb = [0]if you need to index the list right away. Note that Go initializes all elements to0for[]int.c = make(map[string]string): this creates a map withstringas keys and values. Closest thing in Python would be a dictionary:c = {}. And again, you are not constrained by types in Python so you can later doc["foo"] = "bar"without a problem.
NOTE THAT Go slices have different semantics than Python slices. Doing a[1:10] in Go creates a slice that is merely a view on the underlying object, while in Python a[1:10] copies all the elements creating a new list.