Use pointer to a value as a slice

Is it possible to convert a pointer to certain value to a slice?

For example, I want to read single byte from io.Reader into uint8 variable. io.Reader.Read accepts a slice as its argument, so I cannot simply provide it a pointer to my variable as I'd do in C.

I think that creating a slice of length 1, capacity 1 from a pointer is safe operation. Obviously, it should be the same as creating a slice from an array of length 1, which is allowed operation. Is there an easy way to do this with plain variable? Or maybe I do not understand something and there are reasons why this is prohibited?

Answers


A slice is not only a pointer, like an array in C. It also contains the length and capacity of the data, like this:

struct {
  ptr *uint8
  len int
  cap int
}

So, yes, you will need to create a slice. Simplest way to create a slice of the var a uint8 would be []uint8{a}

a := uint8(42)
fmt.Printf("%#v\n", []uint8{a})

(But after rereading your question, this is not a solution as all)

But if you wish to create the slice from the variable, pointing to the same space of memory, you could use the unsafe package. This is most likely to be discouraged.

fmt.Printf("%#v\n", (*[1]uint8)(unsafe.Pointer(&a))[:] )

Need Your Help

SMSLib. Service.getInstance().stopService() doesn't work

java smslib

Im using SMSlib library to send sms from USB 3G Modem ZTE MF180.

Press Enter key to continue with conditions in JavaScript

javascript jquery html keyboard

i want a javascript function or solution that will be click button when press enter key. but it have some conditions as shown in this link http://i.stack.imgur.com/EWUed.png

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.