英文:
Go: basic for loop and strconv
问题
我是你的中文翻译助手,以下是翻译好的内容:
我是Go语言的新手,有一些基础问题想要问一下,我们如何理解这个函数。我们需要使用"strconv"来解决这个问题。
package main
import (
    "fmt"
    "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")
}
输出应该如下所示:
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
我们只需要编写一个main函数和一个简单的for循环即可得到结果。
英文:
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
得分: 0
这是一种实现方法:
fmt.Println("开始会话")
defer fmt.Println("房间空了")
for i := 0; i < 6; i++ {
	s := Student{Name: "学生" + strconv.Itoa(i)}
	s.Present()
	defer s.Leave()
}
fmt.Println("会话结束")
延迟执行的函数会在函数返回时按相反的顺序执行。
英文:
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")
The deferred functions are executed on return from the function in reverse order.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论