加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang导入包

发布时间:2020-12-16 09:22:32 所属栏目:大数据 来源:网络整理
导读:我对Golang有一些问题,包括包.我有那个结构 src/├── hello_world│?? ├── hello.go│?? └── math│?? └── add.go hello.go文件包含以下代码: package mainimport ( "fmt" math "hello_world/math")func main() { fmt.Println("Hello World") x
我对Golang有一些问题,包括包.我有那个结构

src/
├── hello_world
│?? ├── hello.go
│?? └── math
│??     └── add.go

hello.go文件包含以下代码:

package main

import (
    "fmt"
    math "hello_world/math"
)

func main() {
    fmt.Println("Hello World")
    x := math.add(6,5)
}

并添加.go

package math

func add(x,y int) int {
    return x + y
}

当我跑去打招呼时我会看到:

evgen@laptop:~/go/src/hello_world$go run hello.go 
# command-line-arguments
./hello.go:10: cannot refer to unexported name math.add
./hello.go:10: undefined: "hello_world/math".add

GOPATH:

evgen@laptop:~/go/src/hello_world$echo $GOPATH
/home/evgen/go

如何解决?谢谢!

解决方法

在包之外,只能访问和引用导出的标识符,即以大写字母开头的标识符.

所以最简单的解决方法是通过在math.go中将其名称更改为Add()来导出math.add()函数:

func Add(x,y int) int {
    return x + y
}

当然,当你从main.go中提到它时:

x := math.Add(6,5)

作为旁注,请注意,在导入hello_world / math包时,您不必指定新名称来引用其导出的标识符:默认情况下,它将是其导入路径的最后一部分,因此这相当于你的进口:

import (
    "fmt"
    "hello_world/math"
)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读