go在同包下怎么访问不同文件下的变量

axing42 · 2020-06-27 23:16:31 · 2473 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2020-06-27 23:16:31 的主题,其中的信息可能已经有所发展或是发生改变。

环境 Linux dan 4.15.0-91-generic #92-Ubuntu SMP Fri Feb 28 11:09:48 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

./main.go

package main

import (
 "fmt"
 "net/http"
)

func home(w http.ResponseWriter, r *http.Request) {
 _, _ = w.Write([]byte("<h1>地址为: " + r.URL.Path + " 你好,世界!</h1>"))
 //fmt.Printf("来访者: Method:%v Path:%v Scheme:%v \n", r.Method, r.URL.Path, r.URL.Scheme)
}
func show(w http.ResponseWriter, r *http.Request) {
 imgPath := getRandPath("/root/tp8")
 http.ServeFile(w, r, imgPath)
}

func main() {
 http.HandleFunc("/home", home)
 http.HandleFunc("/p", show)
 fmt.Println("服务器开启成功! http://localhost/home")
 err := http.ListenAndServe(":80", nil)
 if err != nil {
  panic(err)
 }
}

./t.go

package main

import (
 "fmt"
 "net/http"
)

func home(w http.ResponseWriter, r *http.Request) {
 _, _ = w.Write([]byte("<h1>地址为: " + r.URL.Path + " 你好,世界!</h1>"))
 //fmt.Printf("来访者: Method:%v Path:%v Scheme:%v \n", r.Method, r.URL.Path, r.URL.Scheme)
}
func show(w http.ResponseWriter, r *http.Request) {
 imgPath := getRandPath("/root/tp8")
 http.ServeFile(w, r, imgPath)
}

func main() {
 http.HandleFunc("/home", home)
 http.HandleFunc("/p", show)
 fmt.Println("服务器开启成功! http://localhost/home")
 err := http.ListenAndServe(":80", nil)
 if err != nil {
  panic(err)
 }
}
root@dan:~/gocode/src/8niWang# cat t.go
package main

import (
 "io/ioutil"
 "log"
 "math/rand"
 "time"
)

func ReadAllDir(path string) {
 //path = strings.Replace(path, "/", "\\", -1)
 FileInfo, err := ioutil.ReadDir(path)
 if err != nil {
  log.Fatalln("读取文件夹出错")
 }
 // 多协程遍历目录
 for _, fileInfo := range FileInfo {
  if fileInfo.IsDir() {
   ReadAllDir(path + "/" + fileInfo.Name())
  } else {
   savePath(path + "/" + fileInfo.Name())
  }
 }
 return
}

// 保存文件地址
var sPath []string
var AA int
func savePath(path string) {
 sPath = append(sPath, path)
 return
}

// 从文件切片里随机取一个文件地址
func getRandPath(path string) string {
 ReadAllDir(path)
 arrLen := len(sPath)
 rand.Seed(time.Now().Unix())
 r := rand.New(rand.NewSource(time.Now().UnixNano()))

 return sPath[r.Intn(arrLen)]
}
//func main(){
// path := getRandPath("/root/tp8")
// log.Println(path)
//}

报错: go build main.go

command-line-arguments

./main.go:13:13: undefined: getRandPath


有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2473 次点击  
加入收藏 微博
3 回复  |  直到 2020-06-28 23:47:05
axing42
axing42 · #1 · 5年之前

没有人嘛..............................................

ypengju
ypengju · #2 · 5年之前

你只编译了main.go 没有指定t.go。go build main.go t.go或者在目录下编译整个包go build

axing42
axing42 · #3 · 5年之前
ypengjuypengju #2 回复

你只编译了main.go 没有指定t.go。`go build main.go t.go`或者在目录下编译整个包`go build`

谢谢大佬

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传