duansha7025 2018-04-30 16:49
浏览 85
已采纳

Golang中的多文件项目

I have a project with 2 files :

enter image description here

Here is my main.go file :

package main

import "fmt"
import "math"

func main() {
    xs := []float64{1, 2, 3, 4}
    avg := math.Average(xs)
    fmt.Println(avg)
}

and my math.go :

package math

func Average(xs []float64) float64 {
    total := float64(0)
    for _, x := range xs {
        total += x
    }
    return total / float64(len(xs))
}

But when i do :

> bussiere@kusanagi [06:44:01 PM] [~/Workspace/bdrun/TestPack/src]
> -> % go install .
> # _/home/bussiere/Workspace/bdrun/TestPack/src ./main.go:8:9: undefined: math.Average bussiere@kusanagi [06:47:12 PM]
> [~/Workspace/bdrun/TestPack/src]-> % go run main.go
> # command-line-arguments ./main.go:8:9: undefined: math.Average

How comes ?

Regards and thanks

  • 写回答

1条回答 默认 最新

  • doudi8519 2018-04-30 17:03
    关注

    You're close. What you have:

    bin/
    pkg/
      math.go
    src/
      main.go
    

    But this isn't what the go binary expects. Under the src folder should be a folder for each project:

    src/
      myproject/
        math/
          math.go
        main.go
    

    When you want a go file to be in a different package it should be in a folder of the same name as the new package. You'll need to update your math import. import "math" will import the standard library math file. Try import "myproject/math" in your main.go after making the tree structure above.

    You don't have to worry about the pkg or bin folder. You won't normally need to go out of your way to put anything in them.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类