doumo3903 2016-01-31 03:27
浏览 19
已采纳

转到:基本的loop和strconv [关闭]

I'm a freshman for go language, and some basic things i want to ask how can we make sense for this function.
we need to use "strconv" to fix this issue.

  package main

import (
    "fat"
    "strconv"

)
type Student struct {
    Name string
}
func (stu *Student) Leave() {
    fmt.Println(stu.Name + " Leaving")

}

func (stu *Student) Present() {
     fmt.Println("I am " + stu.Name)

}

func main() {
  fmt.Println("Start of session")
  for i := 0; i < 6; i++ {
    s := Student{Name: fmt.Sprintf("Student%d", i)}
    s.Present()
    fmt.Println("Room Empty")
    defer s.Leave()
}
  fmt.Println("End of session")
} 

The output should be like this

Start of session 
I am Student0
I am Student1
I am Student2
I am Student3
I am Student4
I am Student5 
End of session 
Student5 Leaving 
Student4 Leaving 
Student3 Leaving 
Student2 Leaving 
Student1 Leaving 
Student0 Leaving 
Room Empty

We need to write only one main function() and a simple for loop to get the result.

  • 写回答

1条回答 默认 最新

  • doubaolan2842 2016-01-31 06:47
    关注

    Here's one way to do it:

    fmt.Println("Start of session")
    defer fmt.Println("Room Empty")
    for i := 0; i < 6; i++ {
        s := Student{Name: "Student" + strconv.Itoa(i)}
        s.Present()
        defer s.Leave()
    }
    fmt.Println("End of session")
    

    playground example

    The deferred functions are executed on return from the function in reverse order.

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

报告相同问题?

悬赏问题

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