How can I correctly use keyword scoped
?
#8135
-
Hello everyone. I cannot determine which way is good to play with static void M1(params Span<Person> span)
{
ref var thirdOne = ref span[2];
ref readonly var fourthOne = ref span[3];
var slicedSpan = span[1..^1];
M2(ref thirdOne);
M3(in fourthOne);
M4(slicedSpan);
}
static void M2(ref Person person)
{
person = person with { Name = "Foo", Age = 42 };
}
static void M3(ref readonly Person person)
{
Console.WriteLine(person.ToString());
}
static void M4(Span<Person> spanSliced)
{
foreach (ref readonly var element in spanSliced)
{
Console.WriteLine(element.ToString());
}
}
readonly record struct Person(string Name, int Age, bool IsMale); Such usages are often appeared in my code environment. However, all possible places of static void M1(params scoped Span<Person> span) // Here
{
scoped ref var thirdOne = ref span[2]; // Here
scoped ref readonly var fourthOne = ref span[3]; // Here
scoped var slicedSpan = span[1..^1]; // Here
M2(ref thirdOne);
M3(in fourthOne);
M4(slicedSpan);
}
static void M2(scoped ref Person person) // Here
{
person = person with { Name = "Foo", Age = 42 };
}
static void M3(scoped ref readonly Person person) // Here
{
Console.WriteLine(person.ToString());
}
static void M4(scoped Span<Person> spanSliced) // Here
{
foreach (scoped ref readonly var element in spanSliced) // Here
{
Console.WriteLine(element.ToString());
}
}
readonly record struct Person(string Name, int Age, bool IsMale); The compiler doesn't tell me whether such usage is wrong or not. Therefore, I cannot determine which usage is correct or better. Was I missing something for details of keyword I just took a look of source code on Some methods of this type uses Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
There's a nice answer on StackOverflow that tries to explain it. Someone correct me if I'm wrong, but I'm pretty sure it's similar to the following Rust lifetime annotations (note the lack of pub fn append_formatted<'a, 'b>(&'a self, value: &'b [u8]) {
// ...
} |
Beta Was this translation helpful? Give feedback.
scoped
is a little hard to grasp if you don't understand the concept of "lifetimes". It essentially means that the pointer value of the reference (or span) will not be used anywhere past the end of the containing method. The data may live longer if it's copied elsewhere. So, forAppendFormatted
, since it copies the data from the span into a different buffer, the span's lifetime can be as small as the method.There's a nice answer on StackOverflow that tries to explain it.
Someone correct me if I'm wrong, but I'm pretty sure it's similar to the following Rust lifetime annotations (note the lack of
where 'a : 'b
bounds):