Remove a const qualifier from a variable in D - metaprogramming

I want to create a non-const copy of a variable. I am doing this inside a templated function, which has an in ref input, so the type (T) has the const set. I see a ConstOf function in https://dlang.org/phobos/std_traits.html but I cannot find an inverse so I can get a non-const type from T.

You might be interested in
std.traits.Unqual.
Note that this gives the type with all qualifiers removed, not just const.

If you want to remove all type qualifiers from a variable you can simply do cast() variable which will result in just the base type without any const/immutable/etc.
However beware that this will result in undefined behaviour and should be avoided!
See also: https://dlang.org/spec/const3.html#removing_with_cast

Related

Leave associated type unspecified in trait implementation

I want to leave an associated type specification in a trait implementation for later, as it requires some work. Is there any way I can tell the compiler to ignore the missing associated type?
impl A for B {
type C = todo()!;
}
It throws this error
error: non-type macro in type position: ::core::panic
Rust macros like todo!() aren't magic, they must expand to valid Rust code. In the case of todo() it expands to panic!("not yet implemented: ....") (see src).
If you use a macro in a type, then it must expand to a valid type. Unfortunately, that means you can't have it expand to the equivalent of todo!(): it wouldn't really make sense!
However, instead, you can use () as a placeholder, or even define a custom type alias: type Todo = ().

What is the syntax: `instance.method::<SomeThing>()`?

I read the below syntax from byteorder:
rdr.read_u16::<BigEndian>()
I can't find any documentation which explains the syntax instance.method::<SomeThing>()
This construct is called turbofish. If you search for this statement, you will discover its definition and its usage.
Although the first edition of The Rust Programming Language is outdated, I feel that this particular section is better than in the second book.
Quoting the second edition:
path::<...>, method::<...>
Specifies parameters to generic type, function, or method in an expression; often referred to as turbofish (e.g., "42".parse::<i32>())
You can use it in any kind of situation where the compiler is not able to deduce the type parameter, e.g.
fn main () {
let a = (0..255).sum();
let b = (0..255).sum::<u32>();
let c: u32 = (0..255).sum();
}
a does not work because it cannot deduce the variable type.
b does work because we specify the type parameter directly with the turbofish syntax.
c does work because we specify the type of c directly.

ANGULAR - Property doesn't exist on type object [duplicate]

I am looking at TypeScript code and noticed that they use:
interface Blablabla {
field: Object;
}
What is the benefit of using Object vs any, as in:
interface Blablabla {
field: any;
}
Bit old, but doesn't hurt to add some notes.
When you write something like this
let a: any;
let b: Object;
let c: {};
a has no interface, it can be anything, the compiler knows nothing about its members so no type checking is performed when accessing/assigning both to it and its members. Basically, you're telling the compiler to "back off, I know what I'm doing, so just trust me";
b has the Object interface, so ONLY the members defined in that interface are available for b. It's still JavaScript, so everything extends Object;
c extends Object, like anything else in TypeScript, but adds no members. Since type compatibility in TypeScript is based on structural subtyping, not nominal subtyping, c ends up being the same as b because they have the same interface: the Object interface.
And that's why
a.doSomething(); // Ok: the compiler trusts you on that
b.doSomething(); // Error: Object has no doSomething member
c.doSomething(); // Error: c neither has doSomething nor inherits it from Object
and why
a.toString(); // Ok: whatever, dude, have it your way
b.toString(); // Ok: toString is defined in Object
c.toString(); // Ok: c inherits toString from Object
So Object and {} are equivalents in TypeScript.
If you declare functions like these
function fa(param: any): void {}
function fb(param: Object): void {}
with the intention of accepting anything for param (maybe you're going to check types at run-time to decide what to do with it), remember that
inside fa, the compiler will let you do whatever you want with param;
inside fb, the compiler will only let you reference Object's members.
It is worth noting, though, that if param is supposed to accept multiple known types, a better approach is to declare it using union types, as in
function fc(param: string|number): void {}
Obviously, OO inheritance rules still apply, so if you want to accept instances of derived classes and treat them based on their base type, as in
interface IPerson {
gender: string;
}
class Person implements IPerson {
gender: string;
}
class Teacher extends Person {}
function func(person: IPerson): void {
console.log(person.gender);
}
func(new Person()); // Ok
func(new Teacher()); // Ok
func({gender: 'male'}); // Ok
func({name: 'male'}); // Error: no gender..
the base type is the way to do it, not any. But that's OO, out of scope, I just wanted to clarify that any should only be used when you don't know whats coming, and for anything else you should annotate the correct type.
UPDATE:
Typescript 2.2 added an object type, which specifies that a value is a non-primitive: (i.e. not a number, string, boolean, symbol, undefined, or null).
Consider functions defined as:
function b(x: Object) {}
function c(x: {}) {}
function d(x: object) {}
x will have the same available properties within all of these functions, but it's a type error to call d with a primitive:
b("foo"); //Okay
c("foo"); //Okay
d("foo"); //Error: "foo" is a primitive
Object is more restrictive than any. For example:
let a: any;
let b: Object;
a.nomethod(); // Transpiles just fine
b.nomethod(); // Error: Property 'nomethod' does not exist on type 'Object'.
The Object class does not have a nomethod() function, therefore the transpiler will generate an error telling you exactly that. If you use any instead you are basically telling the transpiler that anything goes, you are providing no information about what is stored in a - it can be anything! And therefore the transpiler will allow you to do whatever you want with something defined as any.
So in short
any can be anything (you can call any method etc on it without compilation errors)
Object exposes the functions and properties defined in the Object class.
any is something specific to TypeScript is explained quite well by alex's answer.
Object refers to the JavaScript object type. Commonly used as {} or sometimes new Object. Most things in javascript are compatible with the object data type as they inherit from it. But any is TypeScript specific and compatible with everything in both directions (not inheritance based). e.g. :
var foo:Object;
var bar:any;
var num:number;
foo = num; // Not an error
num = foo; // ERROR
// Any is compatible both ways
bar = num;
num = bar;
Contrary to .NET where all types derive from an "object", in TypeScript, all types derive from "any". I just wanted to add this comparison as I think it will be a common one made as more .NET developers give TypeScript a try.
Object appears to be a more specific declaration than any. From the TypeScript spec (section 3):
All types in TypeScript are subtypes of a single top type called the
Any type. The any keyword references this type. The Any type is the
one type that can represent any JavaScript value with no constraints.
All other types are categorized as primitive types, object types, or
type parameters. These types introduce various static constraints on
their values.
Also:
The Any type is used to represent any JavaScript value. A value of the
Any type supports the same operations as a value in JavaScript and
minimal static type checking is performed for operations on Any
values. Specifically, properties of any name can be accessed through
an Any value and Any values can be called as functions or
constructors with any argument list.
Objects do not allow the same flexibility.
For example:
var myAny : any;
myAny.Something(); // no problemo
var myObject : Object;
myObject.Something(); // Error: The property 'Something' does not exist on value of type 'Object'.
Adding to Alex's answer and simplifying it:
Objects are more strict with their use and hence gives the programmer more compile time "evaluation" power and hence in a lot of cases provide more "checking capability" and coould prevent any leaks, whereas any is a more generic term and a lot of compile time checks might hence be ignored.
If your data has more than one key and value pair than you must have to use object
because any accept any kind of data which means some case its not better.
for example if you are performing addition of two number means data must be specify as number datatype if u specify string then i will not perform proper addition.
most probably we don't use the any

What does () mean as an argument in a function where a parameter of type T is expected?

I am new to Rust and I was reading the Dining Philosophers' tutorial when I found this:
Mutex::new(())
I don't know what the argument inside new means. I read the documentation for Mutex and I still have no idea what it means. I would appreciate an explanation about what is happening under the hood.
() is the empty tuple, also called the unit type -- a tuple with no member types. It is also the only valid value of said type. It has a size of zero (note that it is still Sized, just with a size of 0), making it nonexistent at runtime. This has several useful effects, one of which is being used here.
Here, () is used to create a Mutex with no owned data -- it's just an unlockable and lockable mutex. If we explicitly write out the type inference with the turbofish operator ::<>, we could also write:
Mutex::<()>::new( () )
That is, we're creating a new Mutex that contains a () with the initial value ().
() is simply a tuple with no values; a 0-tuple. The type and the value are spelled the same, both (). The type is sometimes known as the "unit type"; it used to actually be a distinct type in the compiler, but now is just treated as a degenerate tuple. It is a 0-sized type; objects of this type won't ever actually take up any space, though it is a Sized type, just with a size of 0.
It is used for cases where you need to have a value or a type, but you have nothing relevant to put there. For instance, if you have a function that doesn't return a value, and call it in a place that expects a value, you find that it actually returns the value () of type ().
fn nothing() {}
fn main() {
println!("{:?}", nothing());
}
That prints () (playpen).
Another use is when you have a generic type like Result<T, E>, which indicates a success or failure of some operation, and can hold either the the result of the successful operation, or an error indicating why it failed. Some operations, such as std::io::write which have no value to return if successful but want to be able to indicate an error, will return a std::io::Result<()>, which is actually a synonym for Result<(), std::io::Error>; that allows the function to return Ok(()) in the success case, but some meaningful error when it fails.
You might compare it to void in C or C++, which are also used for a lack of return value. However, you cannot ever write an object that has type void, which makes void much less useful in generic programming; you could never have an equivalent Result<void, Error> type, because you couldn't ever construct the Ok case.
In this case, a Mutex normally wraps and object that you want to access; so you can put that object into the mutex, and then access it from the guard that you get when you lock the mutex. However, in this example there is no actual data being guarded, so () is used since you need to put something in there, and Mutex is generic over the type so it can accept any type.

Const struct assigned to struct

I have a simple function:
StudentType* SortStudentsByName(const StudentType* student, int numStudents)
{
StudentType* returnStudent = new (nothrow) StudentType[numStudents];
returnStudent = student; // error
}
it keeps saying Type const StudentType* cannot be assigned to StudentType*, which is ridiculous because its the same exact type, one is just a constant.
If i remove the const from the function parameter list, it works.
Im not allowed to remove the const though, because that array shouldn't be modified.
A couple important things:
(1) Both arrays are constructed at runtime to the same size, ensured by the other parameter.
(2) bitcopy should handle this, and it handles the non-const version.
Is there any way to make this work, or do i have to do something different?
It is not the same. You are trying to assign const pointer to a non const pointer. Another words: trying to assign Mutable pointer to a constant StudentType to a non-const pointer.
It does make sense to change something that is declared const to no-cont, meaning you could change a value of a constant.
What you are trying to do is to copy one object to another using shallow copy. in order to do so, you must copy object to another object not pointer to a pointer. you have to dereference pointers.:
*returnStudent = *student
Or if structure contains pointer types, shallow copy will not do. You will have to copy each member taking care of copying memory pointers point to, or write copy constructor.

Resources