增加的秒数没有打印出来。

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

Incremented seconds not printing

问题

我正在学习谷歌Go语言(非常有趣),我用来学习的第一个程序是Matt Aimonetti的博客文章:

Go语言中的真实并发

package main

import (
	"fmt"
	"net/http"
	"time"
)

var urls = []string{
	"http://golang.org",
	"http://www.espn.com",
	"http://www.google.com",
}

type HttpResponse struct {
	url      string
	response *http.Response
	err      error
}

func asyncHttpGets(urls []string) []*HttpResponse {
	ch := make(chan *HttpResponse)
	responses := []*HttpResponse{}
	seconds := 0
	for _, url := range urls {
		go func(url string) {
			fmt.Printf("正在获取 %s \n", url)
			resp, err := http.Get(url)
			ch <- &HttpResponse{url, resp, err}
		}(url)
	}

	for {
		select {
		case r := <-ch:
			fmt.Printf("%s 已获取\n", r.url)
			responses = append(responses, r)
			if len(responses) == len(urls) {
				return responses
			}
		case <-time.After(50 * time.Millisecond):
			seconds++
			fmt.Printf(".")
			fmt.Sprintf("%v", seconds)
		}
	}
	return responses
}

func main() {
	results := asyncHttpGets(urls)
	for _, result := range results {
		fmt.Printf("%s 状态: %s\n", result.url, result.response.Status)
	}
}

我想在输出中也打印出毫秒数,所以我在asyncHttpGets方法中创建了一个seconds变量,并在打印“.”的位置进行了递增。

然而,当我运行时它从未显示:

go build concurrency_example.go && ./concurrency_example

输出:

正在获取 http://golang.org 
正在获取 http://www.espn.com 
正在获取 http://www.google.com 
...http://www.google.com 已获取
..http://golang.org 已获取
.........http://www.espn.com 已获取
http://www.google.com 状态: 200 OK
http://golang.org 状态: 200 OK
http://www.espn.com 状态: 200 OK

问题:

为什么秒数计数器没有被打印出来?

如何通过将毫秒转换为秒(作为整数)并转换为字符串来打印它?

这个例子和博客文章中的解释是一个很好的学习经验!

英文:

Am learning Google Go (very interesting, by the way) and the first program I used to learn was Matt Aimonetti's blog post:

Real life concurrency in Go

package main 
import (
&quot;fmt&quot;
&quot;net/http&quot;
&quot;time&quot;
)
var urls = [] string  {
&quot;http://golang.org&quot;,
&quot;http://www.espn.com&quot;,
&quot;http://www.google.com&quot;,
}
type HttpResponse struct {
url 	  string
response  *http.Response
err		  error
}
func asyncHttpGets(urls [] string) [] *HttpResponse {
ch := make(chan *HttpResponse)
responses := [] *HttpResponse{}
seconds := 0
for _, url := range urls {
go func(url string) {
fmt.Printf(&quot;Fetching %s \n&quot;, url)
resp, err := http.Get(url)
ch &lt;- &amp;HttpResponse{url, resp, err}
}(url)
}
for {
select {
case r := &lt;-ch:
fmt.Printf(&quot;%s was fetched\n&quot;, r.url)
responses = append(responses, r)
if len(responses) == len(urls) {
return responses
}
case &lt;- time.After(50 * time.Millisecond):
seconds++
fmt.Printf(&quot;.&quot;)
fmt.Sprintf(&quot;%v&quot;, seconds)
}
}
return responses
}
func main() {
results := asyncHttpGets(urls)
for _, result := range results {
fmt.Printf(&quot;%s status: %s\n&quot;, result.url, result.response.Status)
}
}

I wanted to see the milliseconds also printed in the output so I create a seconds variable inside the asyncHttpGets method and incremented it in the same place that prints the "."

However, it never displays when I run:

 go build concurrency_example.go &amp;&amp; ./concurrency_example

Outputs:

Fetching http://golang.org 
Fetching http://www.espn.com 
Fetching http://www.google.com 
...http://www.google.com was fetched
..http://golang.org was fetched
.........http://www.espn.com was fetched
http://www.google.com status: 200 OK
http://golang.org status: 200 OK
http://www.espn.com status: 200 OK

Question(s):

Why isn't the seconds counter being printed?

How do I print it by converting milliseconds to seconds (as int) and then convert to string?

This example and the explanations in the blog post was a great learning experience!

答案1

得分: 3

问:为什么秒计数器没有被打印出来?

答:因为你使用了fmt.Sprintf,它返回一个格式化的字符串,而不是打印该字符串。你应该使用fmt.Printf。

问:如何通过将毫秒转换为秒(作为整数),然后再转换为字符串来打印它?

答:如果你有一个毫秒值,只需将其除以1000即可得到秒数。fmt.Printf会将其转换为字符串。

英文:

Q: Why isn't the seconds counter being printed?

A: Because you used fmt.Sprintf, which returns a formatted string; it doesn't print that string. Use fmt.Printf.

Q: How do I print it by converting milliseconds to seconds (as int) and then convert to string?

A: If you have a value in milliseconds, simply divide by 1000 to get seconds. fmt.Printf will convert it to a string for you.

答案2

得分: 3

  1. 你正在使用fmt.Sprintf,它返回一个字符串,而不是实际打印它,你应该使用fmt.Printf
  2. 只需使用fmt.Println(ms/1000)即可打印出秒数。
英文:
  1. You're using fmt.Sprintf, it returns a string, doesn't actually print it, you want to use fmt.Printf
  2. Simply fmt.Println(ms/1000) will print the seconds.

答案3

得分: 1

如其他人所提到的问题是你使用了fmt.Sprintf,它根据格式(函数调用的第一个参数)格式化字符串。

fmt.Sprintf("%v", seconds)替换为fmt.Printf("%v\n", seconds)以打印增量值,或者如果要打印毫秒,则替换为fmt.Printf("%v\n", seconds/1000)。也就是说,更好/更准确的方法是使用time包来获取函数开始和时间打印之间的经过时间,如下所示:

package main

import (
  "fmt"
  "net/http"
  "time"
)

var urls = []string{
  "http://golang.org",
  "http://www.espn.com",
  "http://www.google.com",
}

type HttpResponse struct {
  url      string
  response *http.Response
  err      error
}

func asyncHttpGets(urls []string) []*HttpResponse {
  ch := make(chan *HttpResponse)
  responses := []*HttpResponse{}
  for _, url := range urls {
    go func(url string) {
      fmt.Printf("Fetching %s \n", url)
      resp, err := http.Get(url)
      ch <- &HttpResponse{url, resp, err}
    }(url)
  }
  start := time.Now()

  for {
    select {
    case r := <-ch:
      fmt.Printf("%s was fetched\n", r.url)
      responses = append(responses, r)
      if len(responses) == len(urls) {
        return responses
      }
    case t := <-time.After(50 * time.Millisecond):
      fmt.Println(t.Sub(start))
    }
  }
  return responses
}

func main() {
  results := asyncHttpGets(urls)
  for _, result := range results {
    fmt.Printf("%s status: %s\n", result.url, result.response.Status)
  }
}

我们正在收集time.After返回的计时器输出,并减去函数调用时设置的开始时间。我们最终得到一个time.Duration值,可以以多种不同的方式打印。

英文:

As others mentioned the issue is that you used fmt.Sprintf which formats a string according to a format (the first argument of the function call).

Replace fmt.Sprintf(&quot;%v&quot;, seconds) by fmt.Printf(&quot;%v\n&quot;, seconds) to print the incremental value or fmt.Printf(&quot;%v\n&quot;, seconds/1000) if you want to print milliseconds. That said a better/more accurate way to get the elapsed time between the start of the function and when the time prints the time would be to use the time package as shown below:

package main
import (
&quot;fmt&quot;
&quot;net/http&quot;
&quot;time&quot;
)
var urls = []string{
&quot;http://golang.org&quot;,
&quot;http://www.espn.com&quot;,
&quot;http://www.google.com&quot;,
}
type HttpResponse struct {
url      string
response *http.Response
err      error
}
func asyncHttpGets(urls []string) []*HttpResponse {
ch := make(chan *HttpResponse)
responses := []*HttpResponse{}
for _, url := range urls {
go func(url string) {
fmt.Printf(&quot;Fetching %s \n&quot;, url)
resp, err := http.Get(url)
ch &lt;- &amp;HttpResponse{url, resp, err}
}(url)
}
start := time.Now()
for {
select {
case r := &lt;-ch:
fmt.Printf(&quot;%s was fetched\n&quot;, r.url)
responses = append(responses, r)
if len(responses) == len(urls) {
return responses
}
case t := &lt;-time.After(50 * time.Millisecond):
fmt.Println(t.Sub(start))
}
}
return responses
}
func main() {
results := asyncHttpGets(urls)
for _, result := range results {
fmt.Printf(&quot;%s status: %s\n&quot;, result.url, result.response.Status)
}
}

We are collecting the timer output returned by time.After and subtracting the start time we set when the function is called. We end up with a time.Duration value which we can print many different ways.

huangapple
  • 本文由 发表于 2014年6月15日 08:31:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/24225524.html
匿名

发表评论

匿名网友

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

确定