douweng3383 2018-04-12 19:56
浏览 67
已采纳

Golang Gorilla Mux服务器本地软件包导入和未使用问题

I'm testing a simple server app with Gorilla Mux. I keep getting undefined error when running the app. This is the structure of the app

src/ptest/
├── app
│   └── app.go
└── main.go

main.go

package main

import (
    "fmt"
    "ptest/app"
)

func main() {
    fmt.Println("Hello Testing App")
    app := App{}
}

app.go

package app

import (
    "fmt"
    "log"
    "net/http"
    "github.com/gorilla/mux"
)

type App struct {
    Router *mux.Router
}

func (A *App) Run() {
    fmt.Println("Listening at :8080")
    log.Fatal(http.ListenAndServe(":8080", A.Router))
}

As you can see, I have a main that initialized app by importing from ptest/app. But I am getting an error when I go run *go:

# command-line-arguments
./main.go:5:2: imported and not used: "ptest/app"
./main.go:10:9: undefined: App

This is my go env. I am wondering if something not right with my environment?

GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/haha/Library/Caches/go-build"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/haha/go"
GORACE=""
GOROOT="/usr/local/go"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
GCCGO="gccgo"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
  • 写回答

1条回答 默认 最新

  • doumen1883 2018-04-12 19:58
    关注

    Use App{} struct by package name. Your are importing the package but not using it. App struct is declared in app package. that's why the error.

    # command-line-arguments
    ./main.go:5:2: imported and not used: "ptest/app"
    ./main.go:10:9: undefined: App
    

    In your program you are trying to initialize an App{} which does not exist in main.go.

    package main
    
    import (
        "fmt"
        "ptest/app"
    )
    
    func main() {
        fmt.Println("Hello Testing App")
        app := app.App{}
    }
    

    It is well described in Golang Spec for Qualified Identifiers:

    A qualified identifier is an identifier qualified with a package name prefix. Both the package name and the identifier must not be blank.

    QualifiedIdent = PackageName "." identifier .
    

    A qualified identifier accesses an identifier in a different package, which must be imported. The identifier must be exported and declared in the package block of that package.

    math.Sin    // denotes the Sin function in package math
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退