Using recursive links in Go

I want to contain all my commands on the map and the map from the team to the function that performs the task (only the standard distribution table). I started with the following code:

package main

import "fmt"

func hello() {
    fmt.Print("Hello World!")
}

func list() {
    for key, _ := range whatever {
        fmt.Print(key)
    }
}

var whatever = map[string](func()) {
    "hello": hello,
    "list": list,
}

However, it does not compile because there is a recursive link between the function and the structure. Try to forward-declare that the function failed with a redetermination error when it is defined, and the card is at the top level. How do you define such structures and initialize them at the top level without using a function init().

I do not see a good explanation in the definition of language.

  • The existing direct link is for "external" functions, and it does not compile when I try to forward-declare a function.
  • .

: , , init(). , , , .

2: FigmentEngine , . , .

+4
3

FigmentEngine , . , . , , , .

Context. , .

type Context struct {
    commands map[string]func(Context)
}

, :

var context = Context {
    commands: map[string]func(Context) {
        "hello": hello,
        "list": list,
    },
}

, , , :

func hello(ctx Context) {
    fmt.Print("Hello World!")
}

func list(ctx Context) {
    for key, _ := range ctx.commands {
        fmt.Print(key)
    }
}

, :

func main() {
    for key, fn := range context.commands {
        fmt.Printf("Calling %q\n", key)
        fn(context)
    }
}
+1

, Go ( ):

A B, A B. , . A B, A B, , B, , B, . , .

, , , . 1817 , , Go . , .

, , init(). .

+2

list(). .

Sry , " init()": .

0

All Articles