考虑以下简单的main.go
文件:
package main
type myStruct struct {
songs []string
}
func main() {
s1 := myStruct{
songs:[]string{"Master of Puppets", "Battery"}
}
foo(s1)
}
func foo(s myStruct) {
// Does something with s
}
我知道如何测试foo
函数。但是我如何测试主函数是否正确初始化s1
结构并声明foo
函数以s1
作为参数调用?
答案 0 :(得分:-1)
为什么不尝试我们最基本的调试工具:printf。
package main
import "fmt"
type myStruct struct {
songs []string
}
func main() {
s1 := myStruct{songs:[]string{"Master of Puppets", "Battery"}}
foo(s1)
}
func foo(s myStruct) {
// Does something with s
for i:=0;i<len(s.songs);i++ {
fmt.Printf("s.songs[%d]=\"%s\"\n",i, s.songs[i])
}
}
输出:
s.songs[0]="Master of Puppets"
s.songs[1]="Battery"
如果你真的想测试你的结构是否在你的主函数中正确初始化了:
package main
import "fmt"
type myStruct struct {
songs []string
}
func main() {
s1 := myStruct{songs:[]string{"Master of Puppets", "Battery"}}
foo(s1)
for i:=0;i<len(s1.songs);i++ {
fmt.Printf("s1.songs[%d]=\"%s\"\n",i, s1.songs[i])
}
}
func foo(s myStruct) {
// Does something with s
fmt.Printf("foo has finished its work!\n")
}
输出:
foo has finished its work!
s1.songs[0]="Master of Puppets"
s1.songs[1]="Battery"
如果你想确保main()和foo()都使用同一个对象,试试这个:
package main
import "fmt"
type myStruct struct {
songs []string
}
func main() {
s1 := myStruct{songs:[]string{"Master of Puppets", "Battery"}}
foo(&s1)
fmt.Printf("main() says: s1 lives in the address:%p\n",&s1)
}
func foo(s *myStruct) {
// Does something with s
fmt.Printf("foo() says: s lives in the address:%p\n",s)
}
输出:
foo() says: s lives in the address:0x10434120
main() says: s1 lives in the address:0x10434120
下次,请尝试更具体地解决您的问题。
干杯。