0

I am unable to use a struct in package main which has been defined in a different package. Please note that I am importing the other package correctly

I named the struct and its fields starting with a capital letter because I read that in Golang that is how we indicate that it is an exported field. Although it is not required if the package is imported.

fsm.go

package fsm

import (
"fmt"
"strings"
 )
// EKey is a struct key used for storing the transition map.
type EKey struct {
// event is the name of the event that the keys refers to.
Event string

// src is the source from where the event can transition.
Src string
}

test.go

package main

import (
"encoding/json"
"fmt"

"github.com/looplab/fsm"
) 
func main(){
    Transitions := make(map[EKey]string) 
}

Error: undefined EKey

1
  • 1
    While not recommended it is also possible to add a dot in front of the import, in which case "all the package's exported identifiers declared in that package's package block will be declared in the importing source file's file block and must be accessed without a qualifier." read more here Commented Jan 15, 2019 at 10:43

3 Answers 3

8

You have to first import the package whose identifiers you want to refer to:

import "path/to/fsm"

Once you do this, the package name fsm becomes a new identifier in your file block, and you can refer to its exported identifiers (identifiers that start with an uppercase letter) by using a qualified identifier, which is packagename.IdentifierName like this:

Transitions := make(map[fsm.EKey]string)

See related question: Getting a use of package without selector error

Sign up to request clarification or add additional context in comments.

Comments

2

You need to refer to your struct using fsm.EKey

If you want to import it to your local name space, you need a dot before the import path.

import (
   // ....
   . "github.com/looplab/fsm"
)

Now you can refer to your struct directly as EKey

Comments

1

try this

package main

import (
"encoding/json"
"fmt"

"github.com/looplab/fsm"
) 
func main(){
    Transitions := make(map[fsm.EKey]string) 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.