小编icz*_*cza的帖子

错误的值在if语句之外消失

我有以下代码:

if err == nil {
    body, err := ioutil.ReadAll(response.Body)
    if err == nil {
        dataMap := &models.UserResponse{}
        json.Unmarshal(body, &dataMap)
        if dataMap.User == (models.UserId{}) {
            err = fmt.Errorf("unauthorized")
            fmt.Println(err) // when unathorized, prints unauthorized
        }
    }
}

fmt.Println(err) // always prints nil
Run Code Online (Sandbox Code Playgroud)

Println内部if dataMap.User ...打印"unauthorized",而最后Println总是打印nil.

我不知道它为什么会发生,在这个函数的开头err声明var err error.

variables scope go

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

将 map[string]string 嵌入 Go JSON 编组中,无需额外的 JSON 属性(内联)

有没有办法嵌入map[string]string内联?

我得到的是:

{
    "title": "hello world",
    "body": "this is a hello world post",
    "tags": {
        "hello": "world"
    }
}
Run Code Online (Sandbox Code Playgroud)

我的意思是嵌入或内联是预期的结果,如下所示:

    {
    "title": "hello world",
    "body": "this is a hello world post",
    "hello": "world"
}
Run Code Online (Sandbox Code Playgroud)

这是我的代码...我从 yaml 文件加载信息,并希望从上面返回所需格式的 JSON:

这是我的 yaml:

title: hello world
body: this is a hello world post
tags:
  hello: world
Run Code Online (Sandbox Code Playgroud)

这是我的 Go 代码:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"

    "gopkg.in/yaml.v2"
)

type Post struct {
    Title string            `yaml:"title" json:"title"`
    Body  string            `yaml:"body" json:"body"`
    Tags …
Run Code Online (Sandbox Code Playgroud)

json marshalling go

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

此代码使用变量"ok"但未定义

这段代码正在运行,但我不明白如何.

在下面的代码中,hostProxy [host]可能包含也可能不包含函数.我不明白变量"ok"是如何定义的,或者它是如何获得它的值的.它没有在此行之前定义.

if fn, ok := hostProxy[host]; ok {
    fn.ServeHTTP(w, r)
    return
}

if target, ok := hostTarget[host]; ok {
    ....
}
Run Code Online (Sandbox Code Playgroud)

indexing dictionary go

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

为什么指针会产生错误“无效的间接”?

p是一个指向数组的指针arr,我们可以arr通过 using获取数组*p,但是为什么不能通过 using 获取第二个元素*p[2]

它会导致错误:

p[1] 的无效间接(int 类型)

以下代码:

arr := [4]int{1,2,3,4}
var p *[4]int = &arr
fmt.Println(p)     // output &[1 2 3 4]
fmt.Println(*p)    // output [1 2 3 4]
fmt.Println(p[1])  // output 2
fmt.Println(*p[1]) //generate an error:invalid indirect of p[1] (type int)
Run Code Online (Sandbox Code Playgroud)

arrays pointers go

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

golang是否有支持集数据结构的计划?

此功能可以使用'map'实现.

countrySet := map[string]bool{
  "US": true,
  "JP": true, 
  "KR": true,
}
Run Code Online (Sandbox Code Playgroud)

但为了缓解读者的眼球,'set'是必要的数据结构.

countrySet := set[string]{"US", "JP", "KR"}
Run Code Online (Sandbox Code Playgroud)

或者仅使用键初始化'map'.例如:

countrySet := map[string]bool{"US", "JP", "KR"}
Run Code Online (Sandbox Code Playgroud)

golang是否有支持这种语法的计划?

dictionary set go

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

在 Golang 中绘制具有两个半径的圆圈

我环顾四周,但找不到任何对在 golang 中绘制圆圈有用的东西。我想绘制一个具有 2 个给定(内部和外部)半径的绘图,并为它们之间的所有像素着色。

一种可能的方法是遍历每个像素并为其着色,直到创建环。虽然,这似乎非常低效。

对此的任何帮助将不胜感激!:)

image draw go

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

为什么我的go coroutines在处理后被卡住了?

我是Golang的新手.我一直在使用GORM和并发性去读取SQLite数据库并将其写入CSV文件.它工作顺利,但处理完成后,它不会结束主程序并退出.我必须打印command+c退出.我不知道我做错了什么.可能是它正在进入某种阻塞或死锁模式或其他什么.此外,它也不打印再见消息.这意味着它仍在尝试从频道中读取数据.请帮忙.这是代码.

package main

import (
    "fmt"
    "reflect"

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
)

type AirQuality struct {
    // gorm.Model
    // ID      uint   `gorm:"column:id"`
    Index   string `gorm:"column:index"`
    BEN     string `gorm:"column:BEN"`
    CH4     string `gorm:"column:CH4"`
    CO      string `gorm:"column:CO"`
    EBE     string `gorm:"column:EBE"`
    MXY     string `gorm:"column:MXY"`
    NMHC    string `gorm:"column:NMHC"`
    NO      string `gorm:"column:NO"`
    NO2     string `gorm:"column:NO_2"`
    NOX     string `gorm:"column:NOx"`
    OXY     string `gorm:"column:OXY"`
    O3      string `gorm:"column:O_3"`
    PM10    string `gorm:"column:PM10"`
    PM25    string `gorm:"column:PM25"`
    PXY     string `gorm:"column:PXY"`
    SO2     string `gorm:"column:SO_2"`
    TCH     string `gorm:"column:TCH"`
    TOL     string `gorm:"column:TOL"`
    Time    string `gorm:"column:date; …
Run Code Online (Sandbox Code Playgroud)

loops channel go goroutine go-gorm

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

重构代码以按惯用方式使用单个通道

我有以下代码:

package main

import (
    "fmt"
    "time"
)

type Response struct {
    Data   string
    Status int
}

func main() {
    var rc [10]chan Response
    for i := 0; i < 10; i++ {
        rc[i] = make(chan Response)
    }
    var responses []Response

    for i := 0; i < 10; i++ {
        go func(c chan<- Response, n int) {
            c <- GetData(n)
            close(c)
        }(rc[i], i)
    }

    for _, resp := range rc {
        responses = append(responses, <-resp)
    }

    for _, item := …
Run Code Online (Sandbox Code Playgroud)

arrays concurrency channel go slice

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

确定字符串切片上单词出现的次数

很难弄清楚如何使用我编写的 go-lang 代码来计算切片上应用程序或单词的数量。

希望有人能帮我弄清楚如何计算出现的次数?

https://play.golang.org/p/KvgI-lCz_c6

package main

import (
    "fmt"
)

func main() {

    apps := []string{"one", "two", "three", "one", "four"}
    fmt.Println("apps:", apps)

    o := CountOccurence(apps)

    fmt.Println("=== o: ", o)

}

func CountOccurence(apps []string) map[string]int {

    dict := make(map[string]int)
    for k, v := range apps {
        fmt.Println(k, v)

        dict[v] = k
    }

    // fmt.Println("=== dict: ", dict)

    return dict
}
Run Code Online (Sandbox Code Playgroud)

输出以下内容

apps: [one two three one four]
0 one
1 two
2 three
3 one
4 four
=== o:  map[four:4 …
Run Code Online (Sandbox Code Playgroud)

dictionary go slice

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

比赛条件。不知道为什么

当我运行我的代码时出现竞争条件。它是并发安全存储的简单实现。当我将 get() 方法中的接收器更改为(p *storageType). 我糊涂了。我需要一个可以向我解释这种行为的人。

package main

type storageType struct {
    fc    chan func()
    value int
}

func newStorage() *storageType {
    p := storageType{
        fc: make(chan func()),
    }
    go p.run()
    return &p
}

func (p storageType) run() {
    for {
        (<-p.fc)()
    }
}

func (p *storageType) set(s int) {
    p.fc <- func() {
        p.value = s
    }
}

func (p storageType) get() int {
    res := make(chan int)
    p.fc <- func() {
        res <- p.value
    }
    return <-res …
Run Code Online (Sandbox Code Playgroud)

struct pointers go race-condition

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