Function std.range.primitives.put
Outputs e
to r
. The exact effect is dependent upon the two
types. Several cases are accepted, as described below. The code snippets
are attempted in order, and the first to compile "wins" and gets
evaluated.
void put(R, E)
(
ref R r,
E e
);
In this table "doPut" is a method that places e
into r
, using the
correct primitive: r
if R
defines put
, r
if r
is an input range (followed by r
), or r(e)
otherwise.
Code Snippet | Scenario |
---|---|
r |
R specifically accepts an E . |
r |
R specifically accepts an E[] . |
r |
R accepts some form of string or character. put will
transcode the character e accordingly. |
for (; !e |
Copying range E into R . |
Tip
put
should not be used "UFCS-style", e.g. r
.
Doing this may call R
directly, by-passing any transformation
feature provided by Range
. put(r, e)
is prefered.
Example
When an output range's put
method only accepts elements of type
T
, use the global put
to handle outputting a T[]
to the range
or vice-versa.
import std .traits : isSomeChar;
static struct A
{
string data;
void put(C)(C c) if (isSomeChar!C)
{
data ~= c;
}
}
static assert(isOutputRange!(A, char));
auto a = A();
put(a, "Hello");
writeln(a .data); // "Hello"
Example
put
treats dynamic arrays as array slices, and will call popFront
on the slice after an element has been copied.
Be sure to save the position of the array before calling put
.
int[] a = [1, 2, 3], b = [10, 20];
auto c = a;
put(a, b);
writeln(c); // [10, 20, 3]
// at this point, a was advanced twice, so it only contains
// its last element while c represents the whole array
writeln(a); // [3]
Example
Because of auto-decoding, the front
of a string
is a dchar
,
so using put
with char
arrays is disallowed. In order to fill
any char
type array, use byCodeUnit
.
import std .utf : byCodeUnit;
// the elements must be mutable, so using string or const(char)[]
// won't compile
char[] s1 = new char[13];
auto r1 = s1 .byCodeUnit;
put(r1, "Hello, World!");
writeln(s1); // "Hello, World!"
Authors
Andrei Alexandrescu, David Simcha, and Jonathan M Davis. Credit for some of the ideas in building this module goes to Leonardo Maffi.