K
K
kr_ilya2020-10-23 19:07:49
go
kr_ilya, 2020-10-23 19:07:49

How to put the map/array into a separate package?

Started learning golang. It immediately became unclear how to access map if it is in another package.

I did this:
/localisation/localisation.go

package localisation

var l = map[string]string{
  "start_message": "Привет. Я - Бот",
}


func Get(title string)string{
  return l[title]
}


And in the root main.go
package main

import (
  local "./localisation/"
)

local.Get("start_message")


And so, whether it is possible to make somehow that value to receive without using . function, but directly by l[title] ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2020-10-23
@kr_ilya

You can name the variable with a capital letter, then it will be exported and can be accessed directly.
A working example of your code might look like this:
./localization/localization.go

package localization

var L = map[string]string{
  "start_message": "Привет. Я - Бот",
}

main.go
package main

import (
  "fmt"
  local "./localization"
)

func main() {
    fmt.Printf(local.L["start_message"])
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question