小编icz*_*cza的帖子

如果在循环中抛出异常,则使用try-with-resources奇怪的"资源泄漏:流永远不会关闭"

为什么Eclipse给出了一个奇怪的"资源泄漏:zin永远不会关闭"警告以下代码,即使我使用try-with-resources:

Path file = Paths.get("file.zip");
// Resource leak warning!
try (ZipInputStream zin = new ZipInputStream(Files.newInputStream(file))) {
    for (int i = 0; i < 5; i++)
        if (Math.random() < 0.5)
            throw new Exception();
} catch (Exception e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

如果我在代码上修改"任何东西",警告就会消失.下面我列出了3个修改过的版本都没问题(没有警告).


Mod#1:如果我fortry块中删除循环,则警告消失:

// This is OK (no warning)
try (ZipInputStream zin = new ZipInputStream(Files.newInputStream(file))) {
    if (Math.random() < 0.5)
        throw new Exception();
} catch (Exception e) {
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

Mod#2:如果我保留for …

java eclipse warnings compiler-warnings try-with-resources

15
推荐指数
1
解决办法
2764
查看次数

为什么这些字符串的str == str.intern()结果不同?

public static void main(String[] args) {
    String str1 = new StringBuilder("???").append("??").toString();
    System.out.println(str1.intern() == str1);
    String str2 = new StringBuffer("ja").append("va").toString();
    System.out.println(str2.intern() == str2);
}
Run Code Online (Sandbox Code Playgroud)

结果:

 true
 false   
Run Code Online (Sandbox Code Playgroud)

第一个打印true,第二个打印false.为什么结果不同?

java string string-interning

15
推荐指数
2
解决办法
1045
查看次数

去切片 - 容量/长度?

试着从现在的教程中学习,并提出一个非常基本的问题:

 func main() {
  a := make([]int, 5)
  // [0,0,0,0,0] len=5 cap=5

  b := make([]int, 0, 5)
  // [] len=0 cap=5

  c := b[:2]
  // [0,0] len=2 cap=5

  d := c[2:5]
  // [0,0,0] len=3 cap=3
}
Run Code Online (Sandbox Code Playgroud)

为什么c看起来像是[0,0]长度2?b因为它原来并没有被归零[].因此,没有设置cb[:2]零出前两个元素?

另外,为什么容量为d3?非常困惑.

提前致谢.

arrays go slice

15
推荐指数
1
解决办法
4657
查看次数

接口命名约定Golang

我只是发布我的代码:

/*
*  Role will ALWAYS reserve the session key "role".
 */
package goserver

const (
    ROLE_KEY string = "role"
)

type Role string

//if index is higher or equal than role, will pass
type RolesHierarchy []Role

func (r Role) String() string {
    return string(r)
}

func NewRole(session ServerSession) Role {
    return session.GetValue(ROLE_KEY).(Role)
}

func (this Role) IsRole(role Role, hierarchy RolesHierarchy) bool {
    if role == this {
        return true
    }
    if len(hierarchy) == 0 {
        return false
    }
    var …
Run Code Online (Sandbox Code Playgroud)

naming interface naming-conventions go

15
推荐指数
2
解决办法
2万
查看次数

Go有类似Java的ThreadLocal吗?

我使用Go和Gin来设置我的网站,并想知道数据库访问时间.我使用goroutine所以如果不使用类似线程的东西,我必须改变几乎每个函数来做它.Go有很好的方法吗?

go goroutine thread-local-storage

14
推荐指数
1
解决办法
6589
查看次数

如何使用Scanner从特定行号开始读取文件?

我是Go的新手,我正在尝试编写一个逐行读取文件的简单脚本.我还想在某个文件系统上保存进度(即读取的最后一个行号),这样如果同一个文件再次作为脚本输入,它就会从它停止的行开始读取文件.以下是我的开始.

package main

// Package Imports
import (
    "bufio"
    "flag"
    "fmt"
    "log"
    "os"
)

// Variable Declaration
var (
    ConfigFile = flag.String("configfile", "../config.json", "Path to json configuration file.")
)

// The main function that reads the file and parses the log entries
func main() {
    flag.Parse()
    settings := NewConfig(*ConfigFile)

    inputFile, err := os.Open(settings.Source)
    if err != nil {
        log.Fatal(err)
    }
    defer inputFile.Close()

    scanner := bufio.NewScanner(inputFile)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }

    if err := scanner.Err(); err != nil {
        log.Fatal(err)
    } …
Run Code Online (Sandbox Code Playgroud)

file go readfile

14
推荐指数
2
解决办法
7585
查看次数

尝试更新 Go 中的结构时对字段的无效分配

我收到了 linting 错误

ineffective assignment to field Player.Level (SA4005)go-staticcheck
Run Code Online (Sandbox Code Playgroud)

当我尝试使用结构方法LevelUp来更新结构的值时Player.Level

func main() {
    player := Player{
        Name:  "Tom",
        Level: 0,
    }
    player.LevelUp()
    fmt.Printf("Player level %d\n", player.Level)
}

type Player struct {
    Name  string
    Level int
}

func (p Player) LevelUp() {
    p.Level += 1  // linting error here
}
Run Code Online (Sandbox Code Playgroud)

p.Level0打电话后还留着p.LevelUp()。调用更新该方法所附加的结构体字段值的方法的正确方法是什么?

输出:

Player level 0
Run Code Online (Sandbox Code Playgroud)

methods struct go

14
推荐指数
1
解决办法
1万
查看次数

在Go中的函数中定义递归函数

我试图在Go中的另一个函数中定义一个递归函数,但我正在努力获得正确的语法.我正在寻找这样的东西:

func Function1(n) int {
   a := 10
   Function2 := func(m int) int {
      if m <= a {
         return a
      }
      return Function2(m-1)
   }

   return Function2(n)
}
Run Code Online (Sandbox Code Playgroud)

我想将Function2保留在Function1的范围内,因为它正在访问其范围的某些元素.

我怎么能在Go中这样做?

非常感谢

recursion function go

13
推荐指数
2
解决办法
2964
查看次数

在go中查找constant的地址

我们编写了一个程序,通过它我们试图找到一个常量的地址.有可能这样做吗?

package main

func main() {
        const k = 5
        address := &k
}
Run Code Online (Sandbox Code Playgroud)

它给出了一个错误,任何人都可以告诉我们如何找到常量的地址?

pointers constants go

13
推荐指数
2
解决办法
8069
查看次数

用相同的变量替换Sprintf中的所有变量

是否可以使用fmt.Sprintf()相同的值替换格式化字符串中的所有变量?

就像是:

val := "foo"
s := fmt.Sprintf("%v in %v is %v", val)
Run Code Online (Sandbox Code Playgroud)

哪会回来

"foo in foo is foo"
Run Code Online (Sandbox Code Playgroud)

string format printf go

13
推荐指数
1
解决办法
2279
查看次数