Go: 基本的 for 循环和 strconv

huangapple go评论77阅读模式
英文:

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 (
    &quot;fat&quot;
    &quot;strconv&quot;

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

}

func (stu *Student) Present() {
     fmt.Println(&quot;I am &quot; + stu.Name)
     
}

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

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("会话结束")

延迟执行的函数会在函数返回时按相反的顺序执行。

playground示例

英文:

Here's one way to do it:

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

playground example

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

huangapple
  • 本文由 发表于 2016年1月31日 11:27:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/35110003.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定