如何从属性破坏的属性中获取价值?

发布于 2025-02-08 17:48:36 字数 488 浏览 2 评论 0 原文

使用 getProperty()我可以 以这种方式解开我的 struct

struct Person
    name::String
    age::Int32
end

amber = Person("Amber",22)
name = getproperty(amber,:name)
println(name) # Output: Amber

当我这样做时我无法捕获结果:

(; name, age) = amber

如何仅打印 name ?我在文档中找不到它。

With getproperty() I can
unpack my struct this way:

struct Person
    name::String
    age::Int32
end

amber = Person("Amber",22)
name = getproperty(amber,:name)
println(name) # Output: Amber

I'm unable to capture the result when I do:

(; name, age) = amber

How do I print just the name? I couldn't find it in the documentation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

软糯酥胸 2025-02-15 17:48:36

您可以这样做:

julia> (;name)=amber;

julia> name
"Amber"

或者您可以使用参数软件包:

@unpack name = amber

总有最简单的方法:

julia> amber.name
"Amber"

You could do:

julia> (;name)=amber;

julia> name
"Amber"

Or there you could be using Parameters package:

@unpack name = amber

And there is always the easiest way:

julia> amber.name
"Amber"
围归者 2025-02-15 17:48:36

您所做的是破坏 Amber 的属性 name 和 age ,所以
直接使用它们:

println(name) # Output: Amber

它不同于 getProperty()方法,分2种方法:

  • 当您将 name 传递到 getProperty()时,您'经过一个
    符号

      println(typeof(:name))#输出:符号
     
  • 您不必创建不必要的变量即可获得结果:

     #您使用了两次使用的名称!
    名称= getProperty(琥珀色,:名称)
     

它是在GitHub上,该手册要更新以包括属性
破坏分配和多个返回值
这很幽默,因为阅读了链接的文档后,我决定尝试
使用 struct 而不是 Itable 进行破坏的示例,它起作用了!

我进行了一些搜索,发现此 example 在github上。

What you've done is destructure the properties of amber into name and age, so just
use them directly:

println(name) # Output: Amber

It differs from the getproperty() method in 2 ways:

  • When you pass name into getproperty(), you're passing a
    symbol:

    println(typeof(:name)) # Output: Symbol
    
  • You don't have to create an unnecessary variable to get the result:

    # You've used name twice!
    name = getproperty(amber,:name)
    

It was requested on Github that the manual be updated to include property
destructuring right after Destructuring Assignment and Multiple Return Values.
This is humorous, because after reading the linked documentation, I decided to try
the example of destructuring using a struct instead of a iterable, and it worked!

I did some searching and found this example on Github.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文