-
What's wrong? struct Person:
fn who_is(self, name : StringRef, age : Int):
self.name = name
self.age = age
fn hello(self):
info : StringRef = "Hello, " + self.name + " of " + self.age + " years old."
return info
name : StringRef = "Mark"
age : Int = 23
person = Person(name, age)
print(person.hello()) _error: Expression [11]:9:13: 'Person' value has no attribute 'name' error: Expression [11]:10:13: 'Person' value has no attribute 'age' error: Expression [11]:13:9: use of unknown declaration 'info', 'fn' declarations require explicit variable declarations error: Expression [11]:13:14: statements must start at the beginning of a line error: Expression [11]:27:5: use of unknown declaration 'name' error: Expression [11]:27:10: statements must start at the beginning of a line |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey, from String import String
@value
@register_passable("trivial")
struct Person:
# 1) Need to specify its properties
var name: StringRef
var age: Int
# 2) the constructor is __init__ otherwise to use who_is, you need to make it static and return a new Person.
# You can also add the @value decorator to the struct and skip the constructor
#fn __init__(inout self, name: StringRef, age: Int):
# self.name = name
# self.age = age
# 3) your version needed a few changes and also needed the register_passable decorator
@staticmethod
fn who_is(name: StringRef, age: Int) -> Self:
return Self { name: name, age: age }
# 4) StringLiteral can't `add` (__add__) StringRef, so we need to make it String to be able to join everything togehter.
fn hello(self) -> String:
let info: String = String() + "Hello, " + self.name + " of " + self.age + " years old."
return info
var name: StringRef = "Mark"
var age: Int = 23
var person = Person(name, age)
print(person.hello())
var name2: StringRef = "Fred"
var age2: Int = 30
var person2 = Person.who_is(name2, age2)
print(person2.hello()) |
Beta Was this translation helpful? Give feedback.
Hey,
A couple of things happening here. Please, see the notes on the code below: