如何在Chapel中使用`writeThis()`结构

时间:2018-03-16 17:52:46

标签: formatting chapel

我在Chapel有一个课程,我想让它控制它自己的打印声明。所以例如

class Noob {
  var name: string,  experience:int;
  // constructor
}

后来,我想做类似

的事情
me = new Noob('brian', 0)
writeln(me)

> Hi, my name is Brian and I have 0 years experience

看起来this应该会有所帮助,但我无法使用readThis()方法。

1 个答案:

答案 0 :(得分:3)

您需要writeThis(f)方法来覆盖对象的默认writeln行为:

class Noob {
  var name: string,  experience:int;

  proc writeThis(f) {
    f.writef('Hi, my name is %s and I have %t years experience',
             this.name, this.experience);
  }
}

var noob = new Noob('ben', 2);

writeln(noob);

您还可以使用<~>方法中的readWriteThis(f)运算符来处理对象的读取和写入:

class Noob {
  var name: string,  experience:int;

  proc readWriteThis(f) {
    f <~> 'Hi, my name is %s and I have %t years experience'.format(this.name, this.experience);
  }
}