小编Son*_*nia的帖子

Go select语句的优先级解决方法

我希望在两个通道上进行常规监听,当两个通道都耗尽时阻塞.但是,如果两个通道都包含数据,我希望在处理另一个通道之前将其耗尽.

在下面的工作示例中,我希望outexit处理之前将所有内容都耗尽.我使用select没有任何优先顺序的-statement.我如何解决问题,在退出之前处理所有10个输出值?

package main

import "fmt"

func sender(out chan int, exit chan bool){
    for i := 1; i <= 10; i++ {
        out <- i
    } 
    exit <- true
}

func main(){
    out := make(chan int, 10)
    exit := make(chan bool)

    go sender(out, exit)

    L:
    for {
        select {
            case i := <-out:
                fmt.Printf("Value: %d\n", i)
            case <-exit:
                fmt.Println("Exiting")
                break L
        }
    }
    fmt.Println("Did we get all 10? Most likely not")
}
Run Code Online (Sandbox Code Playgroud)

concurrency select channel go

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

Go-复制结构体之间的所有常用字段

我有一个存储JSON的数据库,以及一个提供外部API的服务器,通过HTTP帖子,可以更改此数据库中的值.数据库由内部的不同进程使用,因此具有共同的命名方案.

客户看到的密钥是不同的,但是使用数据库中的密钥(有未公开的密钥)将1:1映射.例如:

这是在数据库中:

{ "bit_size": 8, "secret_key": false }
Run Code Online (Sandbox Code Playgroud)

这是呈现给客户:

{ "num_bits": 8 }
Run Code Online (Sandbox Code Playgroud)

API可以根据字段名称进行更改,但数据库始终具有一致的键.

我在结构中将字段命名为相同,并为json编码器指定了不同的标志:

type DB struct {
    NumBits int  `json:"bit_size"`
    Secret  bool `json:"secret_key"`
}
type User struct {
    NumBits int `json:"num_bits"`
}
Run Code Online (Sandbox Code Playgroud)

我正在使用encoding/jsonMarshal/Unmarshal.

reflect是正确的工具吗?是否有更简单的方法,因为所有键都相同?我在想某种memcpy(如果我保持用户字段的顺序相同).

reflection json go memcpy

16
推荐指数
3
解决办法
1万
查看次数

如何获得模板渲染的结果

我是golang的新手.

这是我的问题:我想得到一个template.Execute的字符串结果,我不想直接执行它到http.ResponsWriter

这是我的代码,它似乎不能很好地工作

package main

import (
    "fmt"
    "os"
    "template"
)

type ByteSlice []byte

func (p *ByteSlice) Write(data []byte) (lenght int, err os.Error) {
    *p = data
    return len(data), nil
}

func main() {
    page := map[string]string{"Title": "Test Text"}
    tpl, _ := template.ParseFile("test.html")
    var b ByteSlice
    tpl.Execute(&b, &page)
    fmt.Printf(`"html":%s`, b)
}
Run Code Online (Sandbox Code Playgroud)

和text.html:

<html>
<body>
    <h1>{{.Title|html}}</h1>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

但我得到的是

"html":</h1>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

templates go

2
推荐指数
1
解决办法
188
查看次数

标签 统计

go ×3

channel ×1

concurrency ×1

json ×1

memcpy ×1

reflection ×1

select ×1

templates ×1