type Animal = ref object
name: string
age: int
proc speak(self: Animal, msg: string) =
echo self.name & " says:" & msg
proc setName(self: Animal, name:string) =
self.name = name
proc incAge(self: Animal) =
self.age += 1
proc `$`(x, y:Animal ): string=
$x.name & " is " & $y.age.int & " old"
var sparky = Animal(name: "Sparky", age: 10)
sparky.setName("John")
sparky.incAge()
echo sparky.$()
I'd like to ask you to at least format this instead of forcing it into a single line. It's intensely difficult to read in this format.
Ideally just use three backticks aka:
```nim
<your code>
```
type Animal = ref object
name: string
age: int
proc speak(self: Animal, msg: string) =
echo self.name & " says:" & msg
proc setName(self: Animal, name:string) =
self.name = name
proc incAge(self: Animal) =
self.age += 1
proc `$`(x:Animal ): string=
$x.name & " is " & $x.age & " years old"
var sparky = Animal(name: "Sparky", age: 10)
sparky.speak("I am eating")
echo sparky
sparky.setName("John")
sparky.incAge()
echo sparky[]
echo sparky
I fixed your program (with beef's help) so that it fits on one line:
type Animal = tuple[name:string;age:int];let speak=(proc(self:var Animal,msg:string)=echo self.name&" says:"&msg);let setName=(proc(self:var Animal,name:string)=self.name=name);let incAge=(proc(self:var Animal)=self.age+=1);let `$`=(proc(x:Animal): string = $x.name & " is " & $x.age & " years old");var sparky=(name:"Sparky",age:10);sparky.speak"I am eating";echo sparky;sparky.setName "John";sparky.incAge;echo sparky;echo sparky
Apart from that, it's easy to understand, right? If you want the output "John is 11 old" from this program, you can change $ to only accept a single Animal, or you can have use this strange line:
echo sparky.`$`(sparky)
The expected $:
proc `$`(x: Animal): string =
$x.name & " is " & $x.age.int & " old"
or:
import std/strformat
proc `$`(x: Animal): string =
&"{x.name} is {x.age} old"
echo type(sparky) # Animal
echo type(sparky[]) # Animal:ObjectType
Since Animal is defined as a ref object, you can deference it get the underlying object, and object types have have default printers in Nim.