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 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题