You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Julia中struct实例构造时类型异常:Person实例变为Shoe类型问题咨询

错误原因

Julia的自定义内部构造函数需要显式调用内置的new方法生成对应结构体的实例,没有显式返回值时,会默认返回函数体最后一行表达式的执行结果。你定义的两个Person构造函数最后一行均为shoe = 某Shoe类型实例,赋值表达式的返回值为等号右侧的Shoe对象,因此最终构造函数返回的都是Shoe类型实例,而非你预期的Person实例。

修复方案

在两个构造函数的最后一行添加new(age, shoe),显式生成Person实例并返回即可,修复后的完整代码如下:

struct Shoe
  size  :: Int64
  brand :: String
end

struct Person
  age  :: Int64
  shoe :: Shoe

  function Person(a::Int64, s::Shoe)
    age  = a
    shoe = s
    new(age, shoe)
  end

  function Person()
    age  = 33
    shoe = Shoe(17,"Nike")
    new(age, shoe)
  end
end

ian = Person(17, Shoe(32,"Puma"))
tom = Person()

println(typeof(ian)) # 输出 Person
println(typeof(tom)) # 输出 Person

内容的提问来源于stack exchange,提问作者Bojan Niceno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:24:03