slice

What is the simplest way to expand a slice to its capacity?

有些话、适合烂在心里 提交于 2020-08-27 04:15:15
问题 I have a program that uses a buffer pool to reduce allocations in a few performance-sensitive sections of the code. Something like this: play link // some file or any data source var r io.Reader = bytes.NewReader([]byte{1,2,3}) // initialize slice to max expected capacity dat := make([]byte, 20) // read some data into it. Trim to length. n, err := r.Read(dat) handle(err) dat = dat[:n] // now I want to reuse it: for len(dat) < cap(dat) { dat = append(dat, 0) } log.Println(len(dat)) // add it

Best way to swap variable values in Go?

此生再无相见时 提交于 2020-08-22 09:37:07
问题 Is it possible to swap elements like in python? a,b = b,a or do we have to use: temp = a a = b b = temp 回答1: Yes, it is possible. Assuming a and b have the same type, the example provided will work just fine. For example: a, b := "second", "first" fmt.Println(a, b) // Prints "second first" b, a = a, b fmt.Println(a, b) // Prints "first second" Run sample on the playground This is both legal and idiomatic, so there's no need to use an intermediary buffer. 回答2: Yes it is possible to swap

Reshape jagged array and fill with zeros

旧时模样 提交于 2020-08-10 01:14:27
问题 The task I wish to accomplish is the following: Consider a 1-D array a and an array of indices parts of length N . Example: a = np.arange(9) parts = np.array([4, 6, 9]) # a = array([0, 1, 2, 3, 4, 5, 6, 7, 8]) I want to cast a into a 2-D array of shape (N, <length of longest partition in parts>) , inserting values of a upto each index in indx in each row of the 2-D array, filling the remaining part of the row with zeroes, like so: array([[0, 1, 2, 3], [4, 5, 0, 0], [6, 7, 8, 0]) I do not wish

Efficient allocation of slices (cap vs length)

我们两清 提交于 2020-07-30 10:56:29
问题 Assuming I am creating a slice, which I know in advance that I want to populate via a for loop with 1e5 elements via successive calls to append : // Append 1e5 strings to the slice for i := 0; i<= 1e5; i++ { value := fmt.Sprintf("Entry: %d", i) myslice = append(myslice, value) } which is the more efficient way of initialising the slice and why: a. declaring a nil slice of strings? var myslice []string b. setting its length in advance to 1e5 ? myslice = make([]string, 1e5) c. setting both its

Insert vertical slices into array

狂风中的少年 提交于 2020-07-09 17:11:32
问题 In a recent post I demonstrated how to use array arguments in the Application.Index() function (instead of single indices) to rearrange the current columns order in any direction (switch columns, omit/delete columns). Application.Index(data, {vertical rows array}, {horizontal columns array}) This approach doesn't need loops and allows to get any new column order defined just by listing the new column positions, in OP e.g. via Array(1, 4, 2) in other words the 1st column, (the 3rd one omitted