如题在lesson目录下有
package lesson
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
以及
package lesson
import (
"math"
)
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return c.Radius * c.Radius * math.Pi
}
我现在写了一个基础的
package lesson
import (
"fmt"
)
func Say(s string) {
fmt.Println(s)
}
想让计算长方形和圆的对象都有say这个方法,在import的时候回说不允许import 循环,请问遇到这种情况,在同名package下应该怎么解决?
同一个package下,虽然文件不同,但还是算一个工程吧。不用import,直接可以调用里面的函数吧。
同一个package下引用方法不用前置包名。不知道你是不是下面这个意思?
参考代码:
package lesson
import (
"math"
)
type Circle struct {
Radius float64
}
func (c *Circle) Area() float64 {
return c.Radius * c.Radius * math.Pi
}
package lesson
type Rectangle struct {
Width, Height float64
}
func (r *Rectangle) Area() float64 {
return r.Width * r.Height
}
package lesson
import (
"fmt"
)
func Say(s string) {
fmt.Println(s)
var obj = &Rectangle{Width: 2.0, Height: 3.0}
fmt.Println(obj.Area())
}
package main
import "test/lesson"
func main() {
lesson.Say("abc")
}
go 里面一个目录为一个package, 一个package级别的func, type, 变量, 常量, 这个package下的所有文件里的代码都可以随意访问, 也不需要首字母大写.
如果是同一个包下的,只要方法名或者结构首字母大写,直接可以调用,不必引用包!