Direct conversion between slice of string vs slice of subtype of string

Hello folks,

i’ve got a subtype of string, called “Key”, with some additional semantics (some funcs for splitting out components or creating new keys of others …):

type Key string
func (k Key) Foo() {...}

Assinging strings to keys and back is trivial ( k := Key(str) vs s := string(k) ), but with slices
that doesn’t seem to work that way. So, always have to copy slices element by element :frowning:

Theorectically, string and Key should be convertible to each other, since both in the end are just string.

Is there any way to do the conversion w/o explicitly copying one slice to another, element by element ?

I’m not sure if you fully aware of how slices actually have an underlying array as a data-structure? This example demonstrates differences between assigning or copying a slice (using builtin copy-function), play with the t-boolean I set up and experiment when changing keys1 actually changes keys2 as well because of the same underlying array:

(This does not solve your problem yet. It just illustrates the underlying array and the pointers involved.)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.