carbon-lang

How to print more than one value in the same line?


A simple example

Print("This is a number {0}", 1) // results in 4

How can I print 1 2 3 in the same line?

I have tried

Print(1, 2, 3) // Does not work

The forloop also does not work.

The while loop below prints the elements but each in a separate line since we do not have control over the line feed character \n:

fn Main() -> i32 {
    var a: [i32;3] = (1, 2, 3); // Define array containing the numbers 1,2,3
    var i:i32 =0;
    while(i<3){
        Print("{0}", a[i]);
        i= i+1;
    }
  return 0;
}

which results in

  1
  2
  3

here is the code

How can I get 1 2 3?


Solution

  • Short explanation: Providing more than 2 arguments to Print is currently not supported, so is not including a line break.

    Details

    This is definitely something that will change in the future, as the language is in its early design phases. You can find the source for Print as an instrinsic (non-carbon native) here: https://github.com/carbon-language/carbon-lang/blob/trunk/explorer/interpreter/type_checker.cpp#L2297

            case IntrinsicExpression::Intrinsic::Print:
              // TODO: Remove Print special casing once we have variadics or
              // overloads. Here, that's the name Print instead of __intrinsic_print
              // in errors.
              if (args.size() < 1 || args.size() > 2) {
                return CompilationError(e->source_loc())
                       << "Print takes 1 or 2 arguments, received " << args.size();
              }
              CARBON_RETURN_IF_ERROR(ExpectExactType(
                  e->source_loc(), "Print argument 0", arena_->New<StringType>(),
                  &args[0]->static_type(), impl_scope));
              if (args.size() >= 2) {
                CARBON_RETURN_IF_ERROR(ExpectExactType(
                    e->source_loc(), "Print argument 1", arena_->New<IntType>(),
                    &args[1]->static_type(), impl_scope));
              }
    

    If you look at the code you will also see that the type of input variable is limited to just integer types. It would be easy enough create a PR to manually add support for 2-3 if you want :)