相关疑难解决方法(0)

单值上下文中的多个值

由于Go中的错误处理,我经常最终得到多个值函数.到目前为止,我管理它的方式非常混乱,我正在寻找编写更清晰代码的最佳实践.

假设我有以下功能:

type Item struct {
   Value int
   Name string
}

func Get(value int) (Item, error) {
  // some code

  return item, nil
}
Run Code Online (Sandbox Code Playgroud)

如何item.Value优雅地分配新变量.在介绍错误处理之前,我的函数刚刚返回item,我可以简单地执行此操作:

val := Get(1).Value
Run Code Online (Sandbox Code Playgroud)

现在我这样做:

item, _ := Get(1)
val := item.Value
Run Code Online (Sandbox Code Playgroud)

有没有办法直接访问第一个返回的变量?

error-handling return-value go multiple-return-values

97
推荐指数
4
解决办法
9万
查看次数

在Go中解析来自文本文件的HTTP请求和响应

给定以下文件,该文件包含HTTP请求和HTTP响应的HTTP流水线流。

如何将该文件解析为stream变量?

type Connection struct{
   Request *http.Request
   Response *http.Response
}
stream := make([]Connection, 0)
Run Code Online (Sandbox Code Playgroud)

原始文件:

GET /ubuntu/dists/trusty/InRelease HTTP/1.1
Host: archive.ubuntu.com
Cache-Control: max-age=0
Accept: text/*
User-Agent: Debian APT-HTTP/1.3 (1.0.1ubuntu2)

HTTP/1.1 404 Not Found
Date: Thu, 26 Nov 2015 18:26:36 GMT
Server: Apache/2.2.22 (Ubuntu)
Vary: Accept-Encoding
Content-Length: 311
Content-Type: text/html; charset=iso-8859-1

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /ubuntu/dists/trusty/InRelease was not found on this server.</p>
<hr>
<address>Apache/2.2.22 (Ubuntu) Server at archive.ubuntu.com …
Run Code Online (Sandbox Code Playgroud)

go

4
推荐指数
1
解决办法
3788
查看次数