草庐IT

struct - 戈朗 : type conversion between slices of structs

coder 2023-06-27 原文

此问题如下 another question of mine .

在以下测试代码中,我尝试将 res 转换为 ListSociete 时,我并没有完全弄清楚有什么问题:

import (
    "errors"
    "fmt"
    "github.com/jmcvetta/neoism"
)

type Societe struct {
    Name string
}

type ListSociete []Societe

func loadListSociete(name string) (ListSociete, error) {
    db, err := neoism.Connect("http://localhost:7474/db/data")
    if err != nil {
        return nil, err
    }
    res := []struct {
        Name string `json:"a.name"`
    }{}
    cq := neoism.CypherQuery{
        Statement: `
            MATCH (a:Societe)
            WHERE a.name = {name}
            RETURN a.name
            `,
        Parameters: neoism.Props{"name": name},
        Result:     &res,
    }
    db.Cypher(&cq)
    if len(res) == 0 {
        return nil, errors.New("Page duz not exists")
    }
    r := res[0]
    return ListSociete(res), nil
}

[]struct{Name string} 是否不同于 []struct{Name string json:"a.name" } ?

或者 ListSociete 与 []struct{Name string} 不同吗?

谢谢。

最佳答案

您目前正在处理两种不同的类型:

type Societe struct {
    Name string
}

和匿名者:

struct {
    Name string `json:"a.name"`
}

如果没有标签,这两个将是相同的。 <强> Go Specifications 状态(我强调):

Two struct types are identical if they have the same sequence of fields, and if corresponding fields have the same names, and identical types, and identical tags. Two anonymous fields are considered to have the same name. Lower-case field names from different packages are always different.

所以,你不能在两者之间做简单的转换。此外,您正在转换这两种类型的 slice 这一事实会使转换出现问题。我可以为您看到两个选项:

通过迭代复制:

这是安全且推荐的解决方案,但它也更加冗长和缓慢。

ls := make(ListSociete, len(res))
for i := 0; i < len(res); i++ { 
    ls[i].Name = res[i].Name
}
return ls, nil

不安全的转换:

由于两种类型具有相同的底层数据结构,因此有可能进行不安全的转换。
不过,这以后可能会在您面前爆发。警告!

return *(*ListSociete)(unsafe.Pointer(&res)), nil

Playground 示例: http://play.golang.org/p/lfk7qBp2Gb

关于struct - 戈朗 : type conversion between slices of structs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24642148/

有关struct - 戈朗 : type conversion between slices of structs的更多相关文章

  1. ruby-on-rails - Rails/Mongoid 与 Struct 的关系问题 - 2

    我正在构建这个图书馆应用程序,它有3个类。国家、图书馆和书籍。国家有许多图书馆,图书馆属于一个国家。图书馆有很多书,书是嵌入图书馆的。但是,当我执行此auto_pick_job时,我们到达top_free_book并调用library.state。由于某种原因,library.state为nil。我希望恢复状态但没有骰子。我调用和创建库的方式如下。所以图书馆将永远属于一个现有的国家。state=Stats.find(x)library=state.libaries.new(info)library.save_optimistic!我也很感激使用Struct的关系帮助。classStat

  2. c - Data_wrap_struct 和标记函数 - 2

    我正在编写一个Ruby扩展,我正在使用函数Data_wrap_struct。为了参与Ruby的标记和清除垃圾收集过程,我需要定义一个例程来释放我的结构,以及一个例程来标记从我的结构到其他结构的任何引用。我通过经典的free函数来释放内存,但我不知道如何使用标记函数。我的结构听起来像这样typedefstruct{intx;inty;}A;typedefstruct{Acollection[10];intcurrent;}B;我认为我需要一个标记函数来标记结构B的collection中的引用。谁能给我看一个例子,看看标记函数是如何工作的? 最佳答案

  3. ruby-on-rails - gem install json 失败,重新定义了 struct timezone/timespec - 2

    我在Windows上使用带有DevKit的Ruby1.9.3(在Win764位上都是32位)。现在我尝试安装rails,但从bundle中得到一个错误。如果我尝试运行(包在提示什么)geminstalljson我收到以下错误消息:D:\RubyTest>geminstalljsonTemporarilyenhancingPATHtoincludeDevKit...Buildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingjson:ERROR:Failedtobuildgemnativeextension.D:

  4. ruby - 为什么我不应该扩展由 Struct.new 初始化的实例? - 2

    我们有一个遗留代码库,其中rubocop报告了一些我永远无法理解的错误:Don'textendaninstanceinitializedbyStruct.new.Extendingitintroducesasuperfluousclasslevelandmayalsointroduceweirderrorsifthefileisrequiredmultipletimes.究竟什么是“多余的类级别”,可能会引入什么样的“怪异错误”?(问是因为显然我们在过去几年没有遇到过任何此类问题。) 最佳答案 Struct.new创建一个匿名类,它

  5. ruby - 如何更改 Struct 属性的默认值? - 2

    根据thedocumentationStruct的未设置属性设置为nil:unsetparametersdefaulttonil.是否可以为特定属性指定默认值?例如,对于以下结构Struct.new("Person",:name,:happy)我希望属性happy默认为true而不是nil。我怎样才能做到这一点?如果我这样做Struct.new("Person",:name,:happy=true)我明白了-:1:syntaxerror,unexpected'=',expecting')'Struct.new("Person",:name,:happy=true)^-:1:warnin

  6. ruby - 什么时候在 Ruby 中使用 Struct 而不是 Hash 更好? - 2

    RubyStruct允许使用一组访问器生成实例:#CreateastructurenamedbyitsconstantCustomer=Struct.new(:name,:address)#=>CustomerCustomer.new("Dave","123Main")#=>#这看起来方便且功能强大,但是,哈希的作用非常相似:Customer={:name=>"Dave",:address=>"123Main"}在哪些现实情况下我应该更喜欢Struct(以及为什么),选择其中一个有哪些注意事项或陷阱? 最佳答案 就我个人而言,当我想

  7. ruby - 什么时候在 Ruby 中使用 Struct 而不是 Hash? - 2

    我没有太多的编程经验。但是,对我来说,Struct似乎有点类似于Hash。Struct可以做什么?有没有什么Struct可以做而Hash不能做的?google了一下,Struct的概念在C中很重要,但我对C了解不多。 最佳答案 结构在以下方面不同于使用HashMap(除了代码的外观):结构具有一组固定的属性,而您将新键添加到散列。调用结构实例上不存在的属性将导致NoMethodError,而从哈希中获取不存在的键的值只会返回nil。不同结构的两个实例永远不会相等,即使结构具有相同的属性并且实例具有相同的值(即Struct.new(:

  8. ruby - 什么时候应该使用 Struct 与 OpenStruct? - 2

    一般来说,与Struct相比,使用OpenStruct有哪些优点和缺点?哪种类型的一般用例适合其中的每一个? 最佳答案 使用OpenStruct,您可以任意创建属性。另一方面,Struct必须在您创建它时定义其属性。选择哪一个应该主要取决于您以后是否需要能够添加属性。考虑它们的方式是将它们作为一方面的哈希和另一方面的类之间的光谱的中间地带。它们暗示了数据之间比Hash更具体的关系,但它们没有类那样的实例方法。例如,一个函数的一堆选项在哈希中是有意义的;他们只是松散地相关。函数所需的姓名、电子邮件和电话号码可以一起打包在Struct或

  9. javascript - 我如何在 Nodejs Buffer 上像 struct union type 一样处理 C? - 2

    我正在尝试在Nodejs上解析一个使用结构联合类型的缓冲区,我该如何在Nodejs上本地处理这个问题?我完全迷路了。typedefunion{unsignedintvalue;struct{unsignedintseconds:6;unsignedintminutes:6;unsignedinthours:5;unsignedintdays:15;//from01/01/2000}info;}__attribute__((__packed__))datetime; 最佳答案 这个联合要么是一个32位整数value,要么是info结构

  10. 戈朗 "Log in to the site and download the xls file"? - 2

    关闭。这个问题需要更多focused.它目前不接受答案。想改进这个问题吗?更新问题,使其只关注一个问题editingthispost.关闭3年前。Improvethisquestion告诉我如何使用Golang登录网站。下载xls文件是得到了,但是为了在Excel表格中有数据,需要登录网站。该站点位于公司的服务器上。如果你能告诉你怎么做。例如,我用来执行此操作的VBA代码。SetoFields=CreateObject("Scripting.Dictionary")WithoFields.Add"login","sdiscor".Add"password","sdiscor"EndWi

随机推荐