doulao7572 2016-06-25 01:36 采纳率: 0%
浏览 83

您如何在主函数中测试代码

Consider the following trivial main.go file:

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
}

I get how I could test the foo function. But how could I test that the main function properly intializes the s1 struct and assert that the foo function get's called with s1 as an argument?

  • 写回答

1条回答 默认 最新

  • dream198731 2016-06-25 20:10
    关注

    Why not try our most basic debug tool: 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\"
    ",i, s.songs[i])
      }
    }
    

    output:

    s.songs[0]="Master of Puppets"
    s.songs[1]="Battery"
    

    In case you really want to test if your structure was properly initialized inside your main function:

    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\"
    ",i, s1.songs[i])
      }
    }
    
    func foo(s myStruct) {
      // Does something with s
      fmt.Printf("foo has finished its work!
    ")
    }
    

    output:

    foo has finished its work!
    s1.songs[0]="Master of Puppets"
    s1.songs[1]="Battery"
    

    If you want to make sure both main() and foo() are working with the same object, try this:

    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
    ",&s1)
    }
    
    func foo(s *myStruct) {
      // Does something with s
      fmt.Printf("foo() says: s lives in the address:%p
    ",s)
    }
    

    output:

    foo() says: s lives in the address:0x10434120
    main() says: s1 lives in the address:0x10434120
    

    Next time, try being more specific on your questions.

    Cheers.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大