D: Cannot seem to create an std.container.Array of const struct pointers - pointers

Suppose I have a struct type Foo. I'm trying to create an std.container.Array of const pointers to Foo. I tried the obvious first:
import std.container;
alias FooArray = Array!(const(Foo*));
However, this causes a compiler error. Then I tried it with fewer parentheses:
alias FooArray = Array!(const Foo*);
But this gave the same error (error instantiating apparently). What am I doing wrong here?

Array probably needs to modify the reference (if not the object).
Try this:
alias FooArray = Array!(const(Foo)*);

Related

Reference a variable of a dataclass in a field with a default_factory

I want to reference a dataclass variable in a lambda function for a default_factory like:
from typing import List
from dataclasses import dataclass, field
#dataclass
class A:
a: float = 1
b: List = field(default_factory = lambda: [a])
but it I get the error that the variable is undefined. How can I solve this?
You have a scoping problem. By the time the lambda function is executed, a isn't visible to it any more, so it doesn't know how to resolve it. See also the much simpler examples in the python docs on delayed lambda execution to understand the issue.
You can fix it by binding a to the lambda's local scope during its creation:
#dataclass
class A:
a: float = 1
b: List = field(default_factory = (lambda a=a: [a]))
Looks a bit weird, but it does the job.

Referencing list element inside of map in Kotlin

I am new to Kotlin and am still trying to learn it. I have been researching this problem for several hours now and still have not figured it out. I want to get an element from inside of a list by it's index. I figured out how to do this with a plain list, like so
val my_list = listOf(1,2,3)
println(my_list.get(0))
The above works, but when I try to do this with a list that is stored inside of a map
val my_list = mutableMapOf<String, Any>()
my_list["set1"] = listOf(1,2,3)
my_list["set2"] = listOf("A","B","C")
my_list["set3"] = listOf("d","e","f")
val sub_list = my_list["set1"]
println(sub_list.get(0))
I get the following error
Unresolved reference. None of the following candidates is applicable
because of receiver type mismatch: #InlineOnly public inline operator
fun <#OnlyInputTypes K, V> Map.get(key: Int): ???
defined in kotlin.collections #SinceKotlin public operator fun
MatchGroupCollection.get(name: String): MatchGroup? defined in
kotlin.text
Note: I primarily use Python, so that is what I am used to. The functionality from Python that I am trying to reproduce in Kotlin is having a dictionary of lists.
The problem is the type declaration of your map, it should be:
val my_list = mutableMapOf<String, List<Any>>()
Any doesn't have a get() method, so there's no way to invoke it.
Even when that problem is solved, you'll probably have to deal with nullability, though, as:
val sub_list = my_list["set1"]
Will return List<Any>?, which means that my_list might not have a value for the specified key. If that's the case, you'll have to do something like:
sub_list?.get(0)?.run { println(it) }
Which in turn, could also cause an exception if the sub_list is empty. That could be solved with something more like:
vsub_list?.firstOrNull()?.run { println(it) }

How to get a slice of references from a vector in Rust?

Somewhere in the API I use I have a function which takes &[&A] as argument but I only have a vector of A objects. When I try to use this function with
following syntax
pub struct A(pub u64);
fn test(a: &[&A]){}
fn main() {
let v = vec![A(1), A(2), A(3)];
let a = &v[..];
test(a);
}
I have a error:
<anon>:12:9: 12:10 error: mismatched types:
expected `&[&A]`,
found `&[A]`
(expected &-ptr,
found struct `A`) [E0308]
I have made some attempts but without any success:
let a = &v[&..]
and
let a = &v[&A]
How can I make &[&A] from Vec<A>?
Short answer: you can't. These types are not compatible with each other.
What you could do if this is really what the API needs is
test(&v.iter().collect::<Vec<_>>());
But this allocates a new vector. If you are the author of the API, consider changing it: &[&T] is a weird type to work with since you need different owners for the slice and the objects in it. &[T] already has a pass-by-reference semantic of the inner objects.

Reflection: Struct by string

Let's assume I have this struct with a method:
package main
import (
"fmt"
"reflect"
)
type MyStruct struct {
}
func (a *MyStruct) AAction() {
fmt.Println("Hello a")
}
Now, if I want to call the method "AAction" by string, I can use reflection (this works):
func main() {
reflect.New(reflect.TypeOf(MyStruct{})).MethodByName("AAction").Call([]reflect.Value{})
}
The problem is, that I don't want to use MyStruct{} as an expression, but as a string. Of course this doesn't work:
func main() {
theStruct := "MyStruct"
theAction := "AAction"
reflect.New(reflect.TypeOf(theStruct)).MethodByName(theAction).Call([]reflect.Value{})
}
because reflect.Typeof(theStruct) would be a string.
I tried reading through the documentation, sadly, I can't find anything very useful.
I found this similar question: Call a Struct and its Method by name in Go?
Under the accepted question, the OP asks:
The issue in my case Is I cant not declare t is typed T, its must be some how I can declare t typed T by the name of T is string "T"
which gets answered by
[...] I would suggest to match the name against the string "T" somewhere in your code [...]
which doesn't solve the problem, as I would still need to call MyStruct{} somewhere.
The question is: is there any way to use a struct by giving the name as a string? (without manually mapping the the name of the struct to the struct)
Working version with using reflect.TypeOf(MyStruct{}):
PlayGround
Not working version, obviously calling the method on a string: PlayGround
Sorry, you can't. The answer is: you could not. There is no builtin or pre-initialized registry of type names.
To get started with reflection (reflect package), you need a value (of the type in question). Based on a string (string name of the type), you can't acquire a value of that type, so you can't get started.
If you do want to do what you want only by a string type name, you need to build your own "registry" prior to doing what you want.

How do I correct a "const mismatch in out variable"?

So I'm currently writing code to access a player's uniqueNetId using:
Class'GameEngine'.static.GetOnlineSubsystem().UniqueNetIdToString(
OnlineSubsystemSteamworks(Class'GameEngine'.static.GetOnlineSubsystem()).LoggedInPlayerId.Uid);
But that leads to this:
Error, Call to 'UniqueNetIdToString', parameter 1: Const mismatch in Out variable
Does anybody have any idea what I'm doing wrong?
It's not actually a const mismatch. The function is expecting a struct and you are passing in a member of the struct instead. Try removing the .Uid, i.e.:
Class'GameEngine'.static.GetOnlineSubsystem().UniqueNetIdToString(
OnlineSubsystemSteamworks(Class'GameEngine'.static.GetOnlineSubsystem()).LoggedInPlayerId);

Resources