JChao
JChao

Reputation: 2309

Setting constants in golang outside of function as how it's done in Python

In Python, we can declare any variable outside of a function. We can simply call

a = 'a string' or b = ['asd', 'sdf', 'dfg']

I'm learning golang and would like to do the same to simply create a variable and assign values to it.

Do I have to do it inside a func? does it have to be in func main?

so far I have

func main() {

  var A_LIST []string
  A_LIST = append(A_LIST, "str1", "str2")

  var B_LIST []string
  B_LIST = append(B_LIST, "str3", "str4")
}

which can build and I can print out the two variables if I write a fmt.Println

but if I want to build this into a .so file so my python scripts can import it, is this the right thing to do?

EDIT (UPDATE): following the suggestion and writing out some code to explain what I'm intending to do

I want to have several lists to categorize my tags. In Python, it would look like:

tag_category1 = ['tag1', 'tag2', 'tag3']
tag_category2 = ['tag4', 'tag5', 'tag6']

The function would take in a list of tags and categorize them.

tags = ['tag1', 'tag3', 'tag6', 'tag7']
new_tags = {}
for tag in tags:
    if tag in tag_category1:
        new_tag['category1'].append(tag)
    elif tag in tag_category2:
        new_tag['category2'].append(tag)
    else:
        new_tag['others'].append(tag)
return new_tags

so the result should be

new_tags = {
    'category1': ['tag1', 'tag3'],
    'category2': ['tag6'],
    'others':['tag7']
}

I wanna write this function in go, and, since this function was originally used in another python script, I want to be able to import it. For that python script, I still have issue finding some util libraries i use in go, so I have to remain using python.

Upvotes: 2

Views: 2685

Answers (1)

blobdon
blobdon

Reputation: 1336

No, you don't have to declare variables inside a function. Though, you can't use append because append is a non-declaration statement, which you can't use outside a function. Instead, you can declare your variables using literals, in this case a slice literal, ie:

var A_LIST = []string{"str1", "str2"}

You can see an example of this in the crypto.go package, beginning on line 42:

var digestSizes = []uint8{
    MD4:        16,
    ... //omitted for this post
    RIPEMD160:  20,

}

See that it works in the playground

If you need to do more then just hard-code the values, this approach doesn't seem very viable. For anything more dynamic, you will need a function. This could be an init() function, main(), or any other function, as long as you are conscious of the scope of the variable when/where you declare it, and the order in which the variables/functions will be initialised/called.

Regarding the .so file and the appropriate place to declare these variable, I don't know. Try different ways and see what does/doesn't work, then try to figure out why.

Upvotes: 1

Related Questions