Nillable attribute in Struct

This code

struct Person
  getter first : String
  getter family : String?
  def initialize(@first)
  end
  def initialize(@first, @family)
  end
end

if Random.rand < 0.5
  prs = Person.new("Foo")
else
  prs = Person.new("Foo", "Bar")
end

if prs.family.nil?
  puts "nil"
else
  puts "not nil"
  puts prs.family.size
end

gives me this error:

20 | puts prs.family.size
                      ^---
Error: undefined method 'size' for Nil (compile-time type is (String | Nil))

however this works:

if Random.rand < 0.5
  x  = "abc"
else
  x = nil
end

if x.nil?
  puts "nil"
else
  puts x
  puts x.size
end

Why is the first one not working and how can I make Struct attributes Nillable and avoid this problem?

See if var - Crystal.

tl;dr

if family = prs.family
  puts "not nil"
  put family.size
else
  puts "nil"
end

EDIT: Fixed link

1 Like

Just a note that this has nothing to do with structs. You can only restrict the type of local variables in this way. So you always have to assign a method call to a variable… Or at least in most cases.

2 Likes

Thanks