相关疑难解决方法(0)

在golang中迭代时更改值

我想我有这些类型:

type Attribute struct {
    Key, Val string
}
type Node struct {
    Attr []Attribute
}
Run Code Online (Sandbox Code Playgroud)

并且我想迭代我的节点的属性来改变它们.

我本以为能够做到:

for _, attr := range n.Attr {
    if attr.Key == "href" {
        attr.Val = "something"
    }
}
Run Code Online (Sandbox Code Playgroud)

但由于attr不是指针,这不起作用,我必须这样做:

for i, attr := range n.Attr {
    if attr.Key == "href" {
        n.Attr[i].Val = "something"
    }
}
Run Code Online (Sandbox Code Playgroud)

有更简单或更快的方式吗?有可能直接从指针中获取指针range吗?

显然,我不想仅仅为迭代更改结构,更详细的解决方案不是解决方案.

arrays for-loop go

137
推荐指数
4
解决办法
6万
查看次数

Go - 附加到结构上的切片不持久

我很难理解什么似乎是一个非常基本的操作。我想创建两个结构,其中一个结构将保存另一个结构的切片。这是一个说明问题的简单示例:

// Post structure
type Post struct {
    User string `bson:"user"`
    Body string `bson:"body"`
}

// User structure
type User struct {
    Name  string `bson:"name"`
    Posts []Post `bson:"posts"`
}

func (u *User) appendPost(post Post) []Post {
    u.Posts = append(u.Posts, post)
    return u.Posts
}

func main() {
    p1 := Post{User: "Jane", Body: "First Jane's post"}
    u := User{Name: "Jane"}

    users := []User{}
    users = append(users, u)

    for _, user := range users {
        user.appendPost(p1)
    }

    // [{Jane []}]
    fmt.Println(users)
}
Run Code Online (Sandbox Code Playgroud)

此代码不会产生错误,也不会产生任何影响。如果我用这样的预定义帖子初始化并附加用户: …

struct append go slice

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

如何修改for循环中的切片?

我的阅读清单中有一篇文章.每篇文章都有属性"FeedURL",其中包含文章来源的网址.当我取消订阅Feed时,我希望能够删除包含该Feed的每篇文章.

type Article struct {
    FeedURL string
    URL     string // should be unique
    // ... more data
}

func unsubscribe(articleList []Article, url string) []Article {
   // how do I remove every Article from articleList that contains url?
}

func main() {
    myArticleList := []Article{
        Article{"http://blog.golang.org/feed.atom", "http://blog.golang.org/race-detector"},
        Article{"http://planet.python.org/rss20.xml", "http://archlinux.me/dusty/2013/06/29/creating-an-application-in-kivy-part-3/"},
        Article{"http://planet.python.org/rss20.xml", "http://feedproxy.google.com/~r/cubicweborg/~3/BncbP-ap0n0/2957378"},
        // ... much more examples
    }

    myArticleList = unsubscribe(myArticleList, "http://planet.python.org/rss20.xml")

    fmt.Printf("%+v", myArticleList)
}
Run Code Online (Sandbox Code Playgroud)

解决这个问题的有效方法是什么?

起初我的代码看起来像这样取消订阅:

func unsubscribe(articleList []Article, url string) []Article {
    for _, article := range articleList {
        if …
Run Code Online (Sandbox Code Playgroud)

go

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

标签 统计

go ×3

append ×1

arrays ×1

for-loop ×1

slice ×1

struct ×1